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
I am using the Terraform archive_file provider to package multiple files into a zip file. It works fine when I define the archive like this: data "archive_file" "archive" { type = "zip" output_path = "./${var.name}.zip" source_dir = "${var.source_dir}" } However I don't want the archive to contain all of...
---- Thanks jamiet, I modified as your comment ---- copy files to temp dir and archive them locals { source_files = ["${var.source_dir}/main.py", "${var.source_dir}/requirements.txt"] } data "template_file" "t_file" { count = "${length(local.source_files)}" template = "${file(element(local.source_files, count...
Terraform
56,916,719
15
I am trying to set up my infrastructure properly with no passwords or keys laying around. AWS RDS has an option to do so, by enabling users(applications) to authenticate with generated tokens. However, in the documentation, one of the steps(this one) requires running a query in the Postgres database to create an user a...
Once you enable IAM authentication for an RDS database user/role, you are no longer able to use password based authentication for that user/role. This means you can either use a less secure password or even just generate a random password (using the random_id resource) that you use to set the master password and first ...
Terraform
55,834,290
15
There is a repeatable configuration that I see in many Terraform projects where the provider is AWS: The configuration of an outbound (egress) rule to allow ALL outbound traffic. As far as I understand, this is the default behavior in AWS as mentioned in the AWS user guide: By default, a security group includes an out...
The documentation for the aws_security_group resource specifically states that they remove AWS' default egress rule intentionally by default and require users to specify it to limit surprises to users: NOTE on Egress rules: By default, AWS creates an ALLOW ALL egress rule when creating a new Security Group inside of a...
Terraform
55,023,605
15
I have a following (simplified) Terraform code: variable "cluster_id" { default = 1 } resource "aws_instance" "instance" { ... some instance properties ... tags { "Name" = "${format("cluster-%02d", var.cluster_id)}" } } And when I run terraform apply the plan shows: tags.Name: "%!d(string=1)" ...
Terraform, pre 0.12, only supports string, list and map types as an input variable so despite you providing an integer (or a float or a boolean) it will be cast to a string. Both Terraform and Go allow you to use the same padding for integers and strings though so you can just use the following to 0 pad the cluster_id:...
Terraform
54,771,137
15
Using Terraform, I am trying to add a keyvault access policy to an application (that is also created in Terraform), which requires an object_it (which is GUID) of that application. In ARM template it looks like this: "objectId": "[reference(variables('myAppResourceId'), '2015-08-31-PREVIEW').principalId]" so Terrafor...
When you read the description for azurerm_key_vault_access_policy property object_id, then you should know it could mean the web app principal Id. And the azurerm_app_service.myApp.id that you put is not the principal Id, it's the app service resource Id. You should put the azurerm_app_service.myApp.identity.principal...
Terraform
54,189,450
15
I'm using azurerm_virtual_machine_extension to bootstrap some virtual machines in azure. All examples i've found show using something similar to: settings = <<SETTINGS { "fileUris": [ "https://my.bootstrapscript.com/script.sh}" ], "commandToExecute": "bash script.sh" } SETTINGS While this works, my...
Yes We Can! Introduction In protected_settings, use "script". Scripts terraform script provider "azurerm" { } resource "azurerm_virtual_machine_extension" "vmext" { resource_group_name = "${var.resource_group_name}" location = "${var.location}" name = "${var.hostname}-...
Terraform
54,088,476
15
I have successfully created an autoscaling group using Terraform. I would like to now find a way to dynamically name the provisioned instances based on index value. For an aws_instance type, it can be easily done by: resource "aws_instance" "bar" { count = 3 tags { Name = "${var.instance_name_gridNode}${co...
AWS autoscaling groups can be tagged as with many resources and using the propagate_at_launch flag those tags will also be passed to the instances that it creates. Unfortunately these are entirely static and the ASG itself has no way of tagging instances differently. On top of this the default scale in policy will not ...
Terraform
50,502,919
15
I've got a Terraform module like this: module "helloworld" { source = "../service" } and ../service contains: resource "aws_cloudwatch_metric_alarm" "cpu_max" { comparison_operator = "GreaterThanOrEqualToThreshold" evaluation_periods = "2" ... etc } How do you override the service variables comparison_operat...
You have to use a variable with a default value. variable "evaluation_periods" { default = 4 } resource "aws_cloudwatch_metric_alarm" "cpu_max" { comparison_operator = "GreaterThanOrEqualToThreshold" evaluation_periods = "${var.evaluation_periods}" } And in your module module "helloworld" { source = "../se...
Terraform
45,097,380
15
I am trying to build out our AWS environments using Terraform but am hitting some issues scaling. I have a repository of just modules that I want to use repeatedly when building my environments and a second repository just to handle the actual implementations of those modules. I am aware of HashiCorp's Github page tha...
The idea of environment unfortunately tends to mean different things to different people and organizations. To some, it's simply creating multiple copies of some infrastructure -- possibly only temporary, or possibly long-lived -- to allow for testing and experimentation in one without affecting another (probably produ...
Terraform
44,288,602
15
I am new to terraform - I have created remote tfstate in s3, and now there are some manual changes too that are done in my AWS infrastructure. I need to import those manual changes into tfstate. I used the import command for some resources, but for some resources such as IAM policy etc, there is no such import command...
Before directly answering this question I think some context would help: Behind the scenes, Terraform maintains a state file that contains a mapping from the resources in your configuration to the objects in the underlying provider API. When you create a new object with Terraform, the id of the object that was created ...
Terraform
43,950,097
15
I have TF templates whose purpose is to create multiple copies of the same cloud infrastructure. For example you have multiple business units inside a big organization, and you want to build out the same basic networks. Or you want an easy way for a developer to spin up the stack that he's working on. The only differen...
You should use a Terraform Module. Creating a module is nothing special: just put any Terraform templates in a folder. What makes a module special is how you use it. Let's say you put the Terraform code for your infrastructure in the folder /terraform/modules/common-infra. Then, in the templates that actually define y...
Terraform
39,803,182
15
Problem The google_project document says the project_id is optional. project_id - (Optional) The project ID. If it is not provided, the provider project is used. However, Terraform complains it is required. gcp.tf data "google_project" "project" { } output "project_number" { value = data.google_project.project.num...
Your 'Workaround' is functionally equivalent to what the documentation suggests. Namely that the provider project should be set, i.e.: provider "google" { project = "..." } You don't include your provider config but, I assume, it doesn't include the default project to be used. So, either|or but, somewhere you need t...
Terraform
70,674,928
14
I'm using minikube locally. The following is the .tf file I use to create my kubernetes cluster: provider "kubernetes" { config_path = "~/.kube/config" } resource "kubernetes_namespace" "tfs" { metadata { name = "tfs" # terraform-sandbox } } resource "kubernetes_deployment" "golang_webapp" { metadata { ...
The kubernetes_ingress resource generate an ingress with an apiVersion which is not supported by your kubernetes cluster. You have to use [kubernetes_ingress_v1][1] resource which looks similar to kubernetes_ingress resource with some diferences. For your example, it will be like this : resource "kubernetes_ingress_v1"...
Terraform
70,497,809
14
I'm creating a Security group using terraform, and when I'm running terraform plan. It is giving me an error like some fields are required, and all those fields are optional. Terraform Version: v1.0.5 AWS Provider version: v3.57.0 main.tf resource "aws_security_group" "sg_oregon" { name = "tf-sg" descripti...
Since you are using Attributes as Blocks you have to provide values for all options: resource "aws_security_group" "sg_oregon" { name = "tf-sg" description = "Allow web traffics" vpc_id = aws_vpc.vpc_terraform.id ingress = [ { description = "HTTP" from_port = 80 to...
Terraform
69,079,945
14
When I run terraform plan it shows a list of changes made out of Terraform and at the end of output, it also informs that "No changes. Your infrastructure matches the configuration.": Note: Objects have changed outside of Terraform Terraform detected the following changes made outside of Terraform since the las...
When Terraform creates a plan, it does two separate operations for each of your resource instances: Read the latest values associated with the object from the remote system, to make sure that Terraform takes into account any changes you've made outside of Terraform. Compare the updated objects against the configuratio...
Terraform
67,666,185
14
For clarification, what I'm trying to do is fire off a Fargate task when theres an item in a specific queue. I've used this tutorial to get pretty much where I am. This worked fine but the problem I ran into was every file upload (the structure of the s3 bucket is s3_bucket_name/{unknown_name}/known_file_names) was res...
SQS doesn't trigger or "push" messages to anything. As mentioned in the comments, AWS Lambda has an SQS integration that can automatically poll SQS for you and trigger a Lambda function with new messages, which you could use to create your Fargate tasks. However I would recommend refactoring your Fargate task like this...
Terraform
66,388,494
14
I am trying to edit Terraform configuration files with Python. I am parsing Terraform files (.tf) using python hcl2 library which returns a python dictionary. I want to add new key/value pairs or change some values in the dictionary. Directly writing to the file is not a good practice since the returned python dictiona...
The python-hcl2 library implements a parser for the HCL syntax, but it doesn't have a serializer, and its API is designed to drop all of the HCL specifics and retain only a basic Python data structure, so it doesn't seem to retain enough information to surgically modify the input without losing details such as comments...
Terraform
65,685,549
14
I have a file for creating terraform resources with helm helm.tf. In this file I create a honeycomb agent and need to pass in some watchers, so I'm using a yaml file for configuration. Here is the snippet from helm.tf: resource "helm_release" "honeycomb" { version = "0.11.0" depends_on = [module.eks] repository =...
You may use templatefile function main.tf resource "helm_release" "honeycomb" { version = "0.11.0" depends_on = [module.eks] repository = "https://honeycombio.github.io/helm-charts" chart = "honeycomb" name = "honeycomb" values = [ templatefile("modules/kubernetes/helm/honeycomb.yml", {...
Terraform
64,696,721
14
I want use EFS with fargate but I have this error when the task start: ResourceInitializationError: failed to invoke EFS utils commands to set up EFS volumes: stderr: Failed to resolve "fs-xxxxx.efs.eu-west-1.amazonaws.com" - check that your file system ID is correct I have checked the file system ID, it is corrects.....
Make sure you have enabled DNS Resolution and DNS hostnames in your VPC. EFS needs both these options enabled to work since it relies on the DNS hostname to resolve the connection. This had me stuck for a while since most documentation on the internet focuses on the security groups for this error. The terraform AWS pro...
Terraform
64,432,002
14
In terraform there is an example to create EC2 machine in aws. # Create a new instance of the latest Ubuntu 20.04 on an # t3.micro node with an AWS Tag naming it "HelloWorld" provider "aws" { region = "us-west-2" } data "aws_ami" "ubuntu" { most_recent = true filter { name = "name" values = ["ubuntu/i...
Yes, you can. In AWS, you use UserData for that which: can be used to perform common automated configuration tasks and even run scripts after the instance starts. In terraform, the corresponding attribute is user_data. To use it to install Jenkins you can try the following: resource "aws_instance" "web" { ami ...
Terraform
63,978,548
14
Since 1995, we have used an update mechanism which cleanly updates and removes software centrally stores all software meta-data internally to manage needs and artifacts from a single source of truth NEVER triggers itself arbitrarily. While we understand terraform has begun reaching out to a registry in a brave reinve...
What you are describing here sounds like the intention of the Provider Installation settings in Terraform's CLI configuration file. Specifically, you can put your provider files in a local filesystem directory of your choice -- for the sake of this example, I'm going to arbitrarily choose /usr/local/lib/terraform, and ...
Terraform
63,680,319
14
I want to add terraform version 0.12.21 in an alpine container, but I can only add 0.11.0 using apk. If I try to add it as the desired version I get the following error: / # apk upgrade terraform==0.12.21-r0 OK: 192 MiB in 66 packages / # apk add terraform==0.12.21-r0 ERROR: unsatisfiable constraints: terraform-0.11...
I havent found an apk solution but I can just download the desired binary and replace the existing one with the following in the dockerfile: # upgrade terraform to 0.12.21 RUN wget https://releases.hashicorp.com/terraform/0.12.21/terraform_0.12.21_linux_amd64.zip RUN unzip terraform_0.12.21_linux_amd64.zip && rm terraf...
Terraform
63,080,980
14
I have installed a version (0.12.24) of Terraform which is later than the required version (0.12.17) specified in our configuration. How can I downgrade to that earlier version? My system is Linux Ubuntu 18.04.
As long as you are in linux, do the following in the terminal: rm -r $(which terraform) Install the previous version: wget https://releases.hashicorp.com/terraform/1.4.4/terraform_1.4.4_linux_amd64.zip unzip terraform_1.4.4_linux_amd64.zip mv terraform /usr/local/bin/terraform terraform --version That's it, my fr...
Terraform
61,901,363
14
I'm trying to check if a variable exists on a template file using terraform template syntax, but I get error that This object does not have an attribute named "proxy_set_header. $ cat nginx.conf.tmpl %{ for location in jsondecode(locations) } location ${location.path} { %{ if location.proxy_set_header } pro...
If you are using Terraform 0.12.20 or later then you can use the new function can to concisely write a check like this: %{ for location in jsondecode(locations) } location ${location.path} { %{ if can(location.proxy_set_header) } proxy_set_header ${location.proxy_set_header}; %{ endif } } %{ endfor } Th...
Terraform
60,224,456
14
Within Octopus Deploy I've setup a Terraform Apply Step using their Apply a Terraform template In my Terraform main.tf file I want to use a connection to run an remote-exec on a Amazon Linux EC2 instance in AWS resource "aws_instance" "nginx" { ami = "${var.aws_ami}" instance_type = "t2.nano" ...
The correct syntax for a "flush heredoc" does not include a dash on the final marker: aws_key_path = <<-EOF #{martinTestPrivateKey} EOF If prior versions were accepting -EOF to end the heredoc then that unfortunately was a bug, which has now been fixed in Terraform 0.12 and so moving forward you must use the syntax as...
Terraform
57,379,491
14
I made some experiments with terraform, kubernetes, cassandra and elassandra, I separated all by modules, but now I can't delete a specific module. I'm using gitlab-ci, and I store the terraform states on a AWS backend. This mean that, every time that I change the infrastructure in terraform files, after a git push, th...
The meaning of this error message is that Terraform was relying on a provider "kubernetes" block inside the k8s-cassandra module in order to configure the AWS provider. By removing the module from source code, you've implicitly removed that configuration and so the existing objects already present in the state cannot b...
Terraform
54,518,488
14
Are there any scripts that automate persistent disks formatting and attaching to the Google Cloud VM instance, instead of doing formatting & mounting steps? The persistent disk is created with Terraform, which also creates a VM and attaches the disk to it with the attached_disk command. I am hoping to run a simple scr...
Have you considered using a startup script on the instance (I presume you can also add a startup-script with Terraform)? You could use an if loop to discover if the disk is formatted, then if not, you could try running the formatting/mounting commands in the documentation you linked (I realise you have suggested you do...
Terraform
53,162,620
14
I have a terraform configuration that correctly creates a lambda function on aws with a zip file provided. My problem is that I always have to package the lambda first (I use serverless package method for this), so I would like to execute a script that package my function and move the zip to the right directory before...
You already proposed the best answer :) When you add a depends_on = ["null_resource.serverless_execution"] to your lambda resource, you can ensure, that packaging will be done before uploading the zip file. Example: resource "null_resource" "serverless_execution" { provisioner "local-exec" { command = "serverless...
Terraform
52,421,656
14
I'm provisioning a single windows server for testing with terraform in AWS. Every time i need to decrypt my windows password with my PEM file to connect. Instead, i chose the terraform argument get_password_data and stored my password_data in tfstate file. Now how do i decrypt the same with interpolation syntax rsadecr...
The password is encrypted using the key_pair you specified when launching the instance, you still need to use it to decrypt as password_data is still just the base64 encoded encrypted password data. You should use ${rsadecrypt(self.password_data,file("/path/to/private_key.pem"))} This is for good reason. You really don...
Terraform
51,094,442
14
I am trying to generate a bunch of files from templates. I need to replace the hardcoded 1 with the count.index, not sure what format terraform will allow me to use. resource "local_file" "foo" { count = "${length(var.files)}" content = "${data.template_file.tenant_repo_multi.1.rendered}" #TODO: Replace 1 wit...
You can iterate through the tenant_repo_multi data source like so - resource "local_file" "foo" { count = "${length(var.files)}" content = "${element(data.template_file.tenant_repo_multi.*.rendered, count.index)}" filename = "${element(var.files, count.index)}" } However, have you considered using the templa...
Terraform
50,301,523
14
I want to create reserved instances for long periods of time like e.g. with one year run time. Does anybody know if Terraform allows to create such reserved instances in AWS? I could now find anything in the Terraform documentation.
Reserved instances in AWS work on a first come first served basis. If you create any on demand instance that happens to match the criteria of your reserved instance then it will use your reserved instance quota first. The AWS docs also explain this: Reserved Instances are automatically applied to running On-Demand I...
Terraform
48,751,593
14
My pipeline sh block: sh "set +e; /terraform/terraform plan -var aws_access_key=${aws_access_key} - var aws_secret_key=${aws_secret_key} -var aws_ami=${ami_id} -var aws_instance_type=${instance_type} -var aws_elb_security_group=${elb_sg} -var aws_ec2_security_group=${ec2_sg} -detailed-exitcode; echo \$? > status"...
First, FYI: single quotes skip variable interpolation in groovy If you want to have a multiple line script in a string, you need to escape endlines in a multi line variable. You need three things: Use triple double strings """. This allows you to have multi-line strings with interpolation (triple single quoted string...
Terraform
48,630,765
14
I need to define a resource in Terraform (v0.10.8) that has a list property that may or may not be empty depending on a variable, see volume_ids in the following definition: resource "digitalocean_droplet" "worker_node" { count = "${var.droplet_count}" [...] volume_ids = [ "${var.volume_size != 0 ? element(di...
Unfortunately this is one of many language shortcomings in terraform. The hacky workaround is to tack an empty list onto your empty list. ${var.volume_size != 0 ? element(concat(digitalocean_volume.worker.*.id , list("")), count.index) : ""}
Terraform
47,412,837
14
I am trying to have a common user_data file for common tasks such as folder creation and certain package install and a separate user_data file for application specific configuration I am trying the below - user_data = "${data.template_file.userdata_common.rendered}", "${data.template_file.userdata_master.rendered}" Wi...
Did you try template_cloudinit_config? Add below codes. data "template_cloudinit_config" "master" { gzip = true base64_encode = true # get common user_data part { filename = "common.cfg" content_type = "text/part-handler" content = "${data.template_file.userdata_common.rendered}" ...
Terraform
43,642,308
14
In terraform, long keys can be specified as follows: resource "aws_iam_role_policy" "foo-policy" { role = "${aws_iam_role.foo-role.name}" name = "foo-policy" policy = <<EOF { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": [ "lo...
You can use terraform's template_file data source for this. Simply write your policy out to a file in a path that your terraform scripts can access, and then create a template_file data source that references it. For example: data "template_file" "policy" { template = "${file("somepath/my-policy.json")}" } And then,...
Terraform
43,526,544
14
I used to use multiple .sh files that ran different "terraform remote config" commands to switch between state files in buckets in different Google Cloud projects for different environments (dev, test and prod). With version 0.9.0, I understand that this now goes into a a .tf file: terraform { backend "gcs" { buc...
At the time of this writing, not all of the remote backends in Terraform have been updated to support state environments. For those that have, each backend has its own conventions for how to represent the now-multiple states in the data store. As of version 0.9.2, the "consul", "s3" and "local" backends have been updat...
Terraform
43,048,050
14
I need to use regular expressions in my Terraform code. The documentation for the replace function says the string if wrapped in a forward slash can be treated as a regex. I've tried the following: Name = "${replace(var.string, var.search | lower(var.search), replace)}" I need to use regex to replace either the string...
The Terraform docs for the replace function state that you need to wrap your search string in forward slashes for it to search for a regular expression and this is also seen in the code. Terraform uses the re2 library to handle regular expressions which does supposedly take a /i flag to make it case insensitive. Howeve...
Terraform
42,808,041
14
I am trying to access one module variable in another new module to get aws instance ids which are created in that module and use them in a module Cloud watch alerts which creates alarm in those instance ids . The structure is something like the below **Amodule #here this is used for creating kafka aws instances* ...
You can use outputs to accomplish this. In your kafka module, you could define an output that looks something like this: output "instance_ids" { value = ["${aws_instance.kafka.*.id}"] } In another terraform file, let's assume you instantiated the module with something like: module "kafka" { source = "./modules/kaf...
Terraform
41,042,096
14
Using Terraform 0.7.7. I have a simple Terraform file with the following: provider "aws" { access_key = "${var.access_key}" secret_key = "${var.secret_key}" region = "${var.region}" } resource "aws_instance" "personal" { ami = "${lookup(var.amis, var.region)}" instance_type = "t2.micro" } reso...
The error is telling you that the keypair already exists in your AWS account but Terraform has no knowledge of it in its state files so is attempting to create it each time. You have two options available to you here. Firstly, you could simply delete it from the AWS account and allow Terraform to upload it and thus all...
Terraform
40,120,065
14
UPDATE: Been working on this off and on among other things. Cannot seem to get a working config w/ two subnets and an SSH bastion. Placing bounty for a full .tf file config that: * creates two private subnets * creates a bastion * spins an ec2 instance on each subnet configured via the bastion (run some arbitrary shell...
Here is a snippet that may help you. This was untested but was pulled from one of my terraform files where I provision VMs in a private subnet. I know this works with one private subnet, I tried to implement two here like your original question. I jump through my NAT instances to hit and provision private subnet boxes ...
Terraform
35,822,830
14
I am working on a aws stack and have some lambdas and s3 bucket ( sample code below) . how to generate zip file for lambda via terrarform. I have seen different styles and probably depends on the version of terraform as well. resource "aws_lambda_function" "my_lambda" { filename = "my_lambda_func.zip" ...
So to give a more up-to-date and use-case based answer, for terraform version 2.3.0, you can apply the following: data "archive_file" "dynamodb_stream_lambda_function" { type = "zip" source_file = "../../lambda-dynamodb-streams/index.js" output_path = "lambda_function.zip" } resource "aws_lambda_function" "my_dy...
Terraform
71,992,754
13
I have two resources: resource "aws_lightsail_instance" "myserver-sig" { name = "myserver-Sig" availability_zone = "eu-west-2a" blueprint_id = "ubuntu_20_04" bundle_id = "nano_2_0" key_pair_name = "LightsailDefaultKeyPair" } and resource "aws_lightsail_instance_public_ports" "my...
You can force the recreation (delete/create or -/+) by using the -replace=ADDRESS argument with terraform plan or terraform apply: terraform apply -replace=aws_lightsail_instance_public_ports.myserver-sig-public-ports This replaces the former workflow of terraform taint <resource_address> followed by a plan and apply....
Terraform
70,772,731
13
I am trying to build in Terraform a Web ACL resource https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/wafv2_web_acl This resource has the nested blocks rule->action->block and rule-> action->count I would like to have a variable which's type allows me to set the action to either count {} or b...
The only marginal improvement I can imagine is to move the dynamic blocks one level deeper, to perhaps make it clear to a reader that the action block will always be present and it's the count or block blocks inside that have dynamic behavior: action { dynamic "count" { for_each = var.block ? [] : [1] ...
Terraform
70,382,612
13
I have a Terraform script that create an Azure Key Vault, imports my SSL certificate (3DES .pfx file with a password), and creates an Application Gateway with a HTTP listener. I'm trying to change this to a HTTPS listener that uses my SSL certificate from KeyVault. I've stepped through this process manually in Azure Po...
I tested 2 scenarios in my environment : Scenario 1: Generating a new certificate in Keyvault and uploading it in application gateway ssl certificate. provider "azurerm" { features{} } data "azurerm_client_config" "current" {} data "azurerm_resource_group" "example"{ name = "ansumantest" } resource "azurerm_u...
Terraform
69,193,030
13
I came across a pattern in couple of terraform code in Github. resource "aws_vpc" "this" I wanted to know how keyword this provides a particular advantage over a named resource. I can't find a Hashicorp documentation on this keyword. https://github.com/terraform-aws-modules/terraform-aws-vpc/blob/3210728ee26665fab6b1f...
No, there is nothing special about this in terms of TF syntax or handling. Its just a name that may indicate that you have only one VPC in your setup. But this is not enforced by TF mechanism. Other common names are main or just vpc.
Terraform
69,126,254
13
Hi I was wondering if we can add an SNS topic from Terraform with Email subscription. So it will be easy to setup Alarms and create SNS topic to send alert to an email with one “Terraform apply” command. Thanks
resource "aws_sns_topic" "topic" { name = "topic-name" } resource "aws_sns_topic_subscription" "email-target" { topic_arn = aws_sns_topic.topic.arn protocol = "email" endpoint = "example@gmail.com" }
Terraform
67,348,642
13
Terraform v0.13.5 provider aws v3.7.0 Backend: AWS S3+DynamoDB terraform plan was aborted, and now it cannot acquire the state lock. I'm trying to release it manually but get error: terraform force-unlock -force xxx-xxx-xx-dddd Failed to unlock state: failed to retrieve lock info: unexpected end of JSON input The s...
Solution: double-check you're in correct terraform workspace.
Terraform
64,694,279
13
I have a tf script for provisioning a Cloud SQL instance, along with a couple of dbs and an admin user. I have renamed the instance, hence a new instance was created but terraform is encountering issues when it comes to deleting the old one. Error: Error, failed to delete instance because deletion_protection is set to ...
Seems like your code going to recreate this sql-instance. But your current tfstate file contains an instance-code with true value for deletion_protection parameter. In this case, you need first of all change value of this parameter to false manually in tfstate file or by adding deletion_protection = true in the code wi...
Terraform
64,611,122
13
I'm receiving this curious error message PlatformTaskDefinitionIncompatibilityException: The specified platform does not satisfy the task definition’s required capabilities I suspect it's something to do with this line although not quite sure file_system_id = aws_efs_file_system.main.id This is my script: provider "aw...
You simply require to upgrade your ecs service to latest version resource "aws_ecs_service" "service" { platform_version = "1.4.0" launch_type = "FARGATE" ... } efs feature is only available on the latest version When you don’t specify platform_version, it will default to LATEST which is set to 1.3.0 which ...
Terraform
61,351,000
13
I didn't find anything useful in the docs. Can this be done with terraform somehow?
Registering a domain name involves a commitment from a Domain Name Registrar for a minimum of 12 months. Tools like Terraform and AWS CloudFormation are used to create, update and delete infrastructure such as networks, EC2 instances and database. While AWS does offer the ability to register domain names (which is done...
Terraform
60,591,937
13
I've been writing reusable modules for an AWS infrastructure. In creating a security group, my approach is to create a generic module for a security group and provide a list of ports in the control code. However, when using count it creates a security group each for every port. Is there a way around this to iterate a s...
To do this in Terraform 0.12 you can use dynamic blocks. In fact, the example given in that documentation link is for adding ingress rules over a list of ports: resource "aws_security_group" "example" { name = "example" # can use expressions here dynamic "ingress" { for_each = var.service_ports content { ...
Terraform
59,154,055
13
I've deployed my infra using Terraform and I noticed that I have some interesting information in the state (terraform.tfstate) file of terraform which I would like to extract. For example $ terraform state show 'packet_device.worker' id = 6015bg2b-b8c4-4925-aad2-f0671d5d3b13 billing_cycle = hourly cr...
You can utilize terraform show -json and jq to get a specific value out of a Terraform state file. terraform show -json <state_file> | jq '.values.root_module.resources[] | select(.address=="<terraform_resource_name>") | .values.<property_name>' You have a state file named terraform.tfstate and a Terraform resource as...
Terraform
57,811,596
13
I have an object containing the list of subnets I want to create. variable "subnet-map" { default = { ec2 = [ { cidr_block = "10.0.1.0/24" availability_zone = "eu-west-1a" } ], lambda = [ { cidr_block = "10.0.5.0/24" availability_zone = "eu-w...
I'm not sure I fully follow all of what you tried here because your initial snippet of var.subnet-map shows it being a map of maps of lists of objects, but later on when you used for_each = var.subnet-map it seems to have treated it as a map of lists instead. Did you remove that extra level of maps (the "default" key) ...
Terraform
57,570,505
13
I'm learning terraform, and want to setup an AWS infrastructure using the tool. We have 3 AWS environments, sandbox, staging, and production, and have existing infrastructure to support these environments. For example, we have 3 separate VPCs for each environment. I want to use terraform import to import the states of ...
I had the same issue and figured out that the order is important. This command works: $ terraform import -var 'environment=sandbox' aws_vpc.my_vpc vpc-1234
Terraform
57,187,782
13
I'm having a set of Terraform files and in particular one variables.tf file which sort of holds my variables like aws access key, aws access token etc. I want to now automate the resource creation on AWS using GitLab CI / CD. My plan is the following: Write a .gitlab-ci-yml file Have the terraform calls in the .gitla...
Which executor are you using for your GitLab runners? You don't necessarily need to use the Docker executor but can use a runner installed on a bare-metal machine or in a VM. If you install the gettext package on the respective machine/VM as well you can use the same method as I described in Referencing gitlab secret...
Terraform
56,461,518
13
I want to deploy my api gateway with terraform using a swagger file to describe my api. The swagger.yaml looks like this: swagger: '2.0' info: version: '1.0' title: "CodingTips" schemes: - https paths: "/api": get: description: "Get coding tips" produces: - application/json x-amazo...
I found out what was wrong. It is a syntactical error in the locals{} block. uri = should be uri: . Using a colon instead of an equal sign. The block then looks like this: locals{ "get_codingtips_arn" = "${aws_lambda_function.get-tips-lambda.invoke_arn}" "x-amazon-codingtips-get-apigateway-integration" = <<EOF # c...
Terraform
54,047,171
13
I am trying to build an AWS EC2 redhat instance using an AWS launch template with Terraform. I can create an launch template with a call to Terraform's resource aws_launch_template. My question is how do I use Terraform to build an EC2 server with the created launch template? What Terraform aws provider resource do I c...
Welcome to Stack Overflow! You can create an aws_autoscaling_group resource to make use of your new Launch Template. Please see the example here for more details. Code: resource "aws_launch_template" "foobar" { name_prefix = "foobar" image_id = "ami-1a2b3c" instance_type = "t2.micro" } resource "aws_autos...
Terraform
53,749,816
13
I've been running containers on ECS, and using AWS Cloudwatch events to notify me when my tasks complete. All of the infrastructure has been created using Terraform. However, I'm unable to get the correct syntax in my event pattern so that I am only notified for non-zero exit codes. The following resource works great, ...
The event pattern syntax is pretty weird, I ran into the same issue. The following will work: { "source": [ "aws.ecs" ], "detail-type": [ "ECS Task State Change" ], "detail": { "lastStatus": [ "STOPPED" ], "stoppedReason": [ "Essential container in task exited" ], "cont...
Terraform
53,015,242
13
I am relatively new to AWS and the beast. After working on API Gateway to Lambda proxy integration I am getting Execution failed due to configuration error: Invalid permissions on Lambda function I followed below setup referred from really well documented terraform documentation and does exactly what was needed for me...
Few learnings from API Gateway Lambda proxy integration API Gateway is deployed in different stages and ARN for API gateway in stage vs on test console is somewhat different. (atleast thats what I got on terraform output) As many documentations and fixes for the problem suggests to explicitly configure detailed path...
Terraform
52,210,516
13
If I get this right, lb_listener only accepts forward as valid action type. https://www.terraform.io/docs/providers/aws/r/lb_listener.html How do I configure a listener to redirect HTTP to HTTPS? i.e. this is the desired state in elb listener:
This functionality was added to the AWS provider and released with 1.33.0. Here's how you'd set the default action on a load balancer listener with the aws_lb_listener resource: resource "aws_lb" "front_end" { # ... } resource "aws_lb_listener" "front_end" { load_balancer_arn = "${aws_lb.front_end.arn}" port ...
Terraform
51,767,917
13
I'm using terraform v.0.11.7. I wants to create 4 subnets (2 public subnets, 2 private subnets) Here's a content of vars.tf variable "region" { default = "ap-south-1" } variable "ami_id" { type = "map" default = "ami-d783a9b8" } variable "credentials" { default = "/root/.aws/credentials" } variable "vpc_cidr...
Better use lists of subnets to reduce the amount of variables. Then you can also use count = length(var.subnets) to get 2 instances of the route table association resource and pick the correct one from the subnets list. variable "subnet_cidrs_public" { description = "Subnet CIDRs for public subnets (length must matc...
Terraform
51,739,482
13
It's been somewhat long I'm trying to automate the deployment of an application gateway using Terraform but it simply fails with an error message. I have made sure all protocol settings to HTTPS. However, I doubt there is something fishy with the PFX certificate. Is it that I'm not supplying the authentication certific...
As mentioned in the azurerm_application_gateway docs you need to add the ssl_certificate_name to your http_listener block when using https.
Terraform
48,825,236
13
I am trying to use a multiline string in the provisioner "remote-exec" block of my terraform script. Yet whenever I use the EOT syntax as outlined in the documentation and various examples I get an error that complains about having: invalid characters in heredoc anchor. Here is an example of a simple provisioner "remo...
Heredocs in Terraform are particularly funny about the surrounding whitespace. Changing your example to the following seems to get rid of the heredoc specific errors: provisioner "remote-exec" { inline = [<<EOF echo hi EOF, <<EOF echo \ hi EOF ] } You shouldn't need multiple heredocs in here at all though as the i...
Terraform
37,886,759
13
My question is similar to this git hub post: https://github.com/hashicorp/terraform/issues/745 It is also related to another stack exchange post of mine: Terraform stalls while trying to get IP addresses of multiple instances? I am trying to bootstrap several servers and there are several commands I need to run on my i...
The solution is to create a resource "null_resource" "nameYouWant" { } and then run your commands inside that. They will run after the initial resources are created: resource "aws_instance" "consul" { count = 3 ami = "ami-ce5a9fa3" instance_type = "t2.micro" key_name = "ansible_aws" tags { Name = "consul...
Terraform
37,865,979
12
I created a YML pipeline using terraform . It uses a script task and returns in output the web app name steps: - script: | [......] terraform apply -input=false -auto-approve # Get the App Service name for the dev environment. WebAppNameDev=$(terraform output appservice_name_dev) # Write...
I solved by adding -raw parameter to terraform output. WebAppNameDev=$(terraform output -raw appservice_name_dev) ref. https://www.terraform.io/docs/cli/commands/output.html
Terraform
66,935,287
12
I have a terraform list a = [1,2,3,4] Is there a way for me to apply a function (e.g. *2) on the list, to get b = [2,4,6,8] I was looking for an interpolation syntax, perhaps map(a, _*2), or even something like variable "b" { count = "${length(a)}" value = "${element(a, count.index)} * 2 } As far as I can see ...
As per @Rowan Jacob's answer, this is now possible in v0.12 using the new for expression. See: https://www.terraform.io/docs/configuration/expressions.html#for-expressions variable "a" { type = "list" default = [1,2,3,4] } locals { b = [for x in var.a : x * 2] } output "local_b" { value = "${local.b}" } giv...
Terraform
51,267,625
12
I am trying to deploy a website container through Terraform. Everything goes right, just the task fails with STOPPED (CannotPullECRContainerError: AccessDeniedException) Here is a copy of my Terraform script: # Specify the provider and access details provider "aws" { region = "${var.aws_region}" a...
So found how to fix the problem. I was missing the following rights in the policy: "ecr:GetAuthorizationToken", "ecr:BatchCheckLayerAvailability", "ecr:BatchGetImage", "ecr:GetDownloadUrlForLayer"
Terraform
48,540,828
12
Running terraform for creatind a key policy in AWS KMS I am getting the error: aws_kms_key.dyn_logs_server_side_cmk: MalformedPolicyDocumentException: The new key policy will not allow you to update the key policy in the future. status code: 400, request id: e34567896780780 There are many posts about this problem bu...
In my case the account id was correct but the user creating the key wasn't included in the Enable IAM User Permissions statement. I had to do this resource "aws_kms_key" "dyn_logs_server_side_cmk" { description = "dyn-logs-sse-cmk-${var.environment}" enable_key_rotation = "true" policy = <<EOF { "Versio...
Terraform
48,509,193
12
Is there any way to start an AWS Database Migration Service full-load-and-cdc replication task through Terraform? Preferably, this would start automatically upon creation of the task. The AWS DMS console provides an option to "Start task on create", and the AWS CLI provides a start-replication-task command, but I'm not...
I've logged an issue for this feature request: Terraform AWS Provider #2083: Support Starting AWS Database Migration Service Replication Task
Terraform
46,920,760
12
How can I get Terraform 0.10.1 to support two different providers without having to run 'terraform init' every time for each provider? I am trying to use Terraform to 1) Provision an API server with the 'DigitalOcean' provider 2) Subsequently use the 'Docker' provider to spin up my containers Any suggestions? Do I nee...
Terraform's current design struggles with creating "multi-layer" architectures in a single configuration, due to the need to pass dynamic settings from one provider to another: resource "digitalocean_droplet" "example" { # (settings for a machine running docker) } provider "docker" { host = "tcp://${digitalocean_d...
Terraform
45,734,925
12
This question is NOT answered. Someone mentioned environment variables. Can you elaborate on this? 5/28/2024 - Simplified the question (below): This is an oracle problem. I have 4 PCs. I need program 1 run on the one machine that has Drive E. Out of the remaining 3 that don't have drive E, I need program 2 run on ONLY...
No sure what you actually want, but you can set a fact for every host in a play with a single looped task (some simulation of global variable): playbook.yml --- - hosts: mytest gather_facts: no vars: tasks: # Set myvar fact for every host in a play - set_fact: myvar: "{{ inventory_hostname }}" ...
Ansible
47,167,446
24
I have been trying to write playbooks where I can run different tasks based on the arch (i.e amd64, arm, ppc64le) that the playbook is running on. I can not figure out how do I get the arch of the system I am running it on. How to figure out the arch of the system in Ansible playbook?
To get the architecture of the system At the command line: ansible HOST -m setup -a 'filter=ansible_architecture' For an x86 architecture host, this would return: HOST | SUCCESS => { "ansible_facts": { "ansible_architecture": "x86_64" }, "changed": false } Here’s a sample playbook that will print...
Ansible
44,713,880
24
I wrote an ansible task to iterate over a list of settings using with_items. Now all my settings are logged when I run ansible. It is very verbose and makes it hard to see what is happening. But, if I disable all the output with no_log, I will have no way to identify specific items when they fail. How could the outp...
There's loop_control for that: - authorized_key: user: "{{ item.user }}" key: "{{ item.key }}" with_items: "{{ ssh_keys }}" loop_control: label: "{{ item.user }}"
Ansible
42,832,530
24
Is it possible to define one notify block for several tasks? In next code snippet notify: restart tomcat defined 3 times, but I want to define it only one time and "apply" to list of tasks - name : template context.xml template: src: context.xml.j2 dest: /usr/share/tomcat/conf/context.xml group: tomcat ...
No, you cannot. Notify sets a trigger to run the specified handler based on the status of the task. There is no "status for a block of tasks" in Ansible hence you cannot define notify for a block. Besides, it wouldn't change anything functionally, only influence the visual appeal (and I would claim by obscuring things ...
Ansible
41,613,343
24
I've been having some trouble with restarting the SSH daemon with Ansible. I'm using the latest software as of May 11 2015 (Ansible 1.9.1 / Vagrant 1.7.2 / VirtualBox 4.3.26 / Host: OS X 10.10.1 / Guest: ubuntu/trusty64) tl;dr: There appears to be something wrong with the way I'm invoking the service syntax. Problem Wi...
As the comments above state, this is an Ansible issue that will apparently be fixed in the 2.0 release. I just changed my handler to use the command module and moved on: - name: restart sshd command: service ssh restart
Ansible
30,162,528
24
I am trying to implement a reducer for Hadoop Streaming using R. However, I need to figure out a way to access certain libraries that are not built in R, dplyr..etc. Based on my research seems like there are two approaches: (1) In the reducer code, install the required libraries to a temporary folder and they will be d...
tl;dr Rscript -e 'install.packages("drat", repos="https://cloud.r-project.org")' You mentioned you are trying to install dplyr into custom lib location on your disk. Be aware that dplyr package does not support that. You can read more in dplyr#4641. Moreover if you are installing private package published in interna...
Ansible
26,985,112
24
I've installed ansible on my Mac using pip as advised by ansible's documentation: https://docs.ansible.com/ansible/latest/installation_guide/intro_installation.html#installing-ansible-on-macos However when I try to run ansible I get the following: zsh: command not found: ansible I've never had this problem when install...
After installing ansible with python3 -m pip install --user ansible, I searched for the ansible binary and found it to be downloaded into ~/Library/Python/3.8/bin. The simplest way is to figure this out is: $ cd ~ $ find . | grep ansible <lines omitted> ./Library/Python/3.8/bin/ansible <lines omitted> From there, its ...
Ansible
63,177,609
23
This is my ansible role: /roles /foo /tasks main.yml <----- I want to split this The main.yml file is really big, so I want to split it into multiple files, and call them in sequence. /roles /foo /tasks run-this-first.yml <--- 1st run-this-last.yml <--- ...
You can do it with include_tasks: /roles /foo /tasks main.yml run-this-first.yml <--- 1st run-this-last.yml <--- last run-this-second.yml <--- 2nd As you can notice that there is also main.yml inside the tasks directory and your main.yml simply contains th...
Ansible
57,648,261
23
I am automating Canonical Kubernetes installation with Ansible. The intallation process required snap to be present on the host. Is there a standard way to install snap packages with Ansible already?
The snap module is available since version 2.8 of Ansible (released May 2019): https://docs.ansible.com/ansible/latest/modules/snap_module.html#snap-module The required task will be: - name: Install conjure-up for Canonical Kubernetes community.general.snap: name: conjure-up classic: yes
Ansible
47,305,658
23
I have a directory: /users/rolando/myfile I want to copy "myfile" to hostname "targetserver" in directory: /home/rolando/myfile What is the syntax in the playbook to do this? Examples I found with the copy command look like it's more about copying a file from a source directory on a remote server to a target directory...
From copy synopsis: The copy module copies a file on the local box to remote locations. - hosts: targetserver tasks: - copy: src: /users/rolando/myfile dest: /users/rolando/myfile
Ansible
44,595,867
23
I have a service call that returns system status in json format. I want to use the ansible URI module to make the call and then inspect the response to decide whether the system is up or down {"id":"20161024140306","version":"5.6.1","status":"UP"} This would be the json that is returned This is the ansible task that ...
This works for me. - name: check sonar web is up uri: url: http://sonarhost:9000/sonar/api/system/status method: GET return_content: yes status_code: 200 body_format: json register: result until: result.json.status == "UP" retries: 10 delay: 30 Notice that result is a ansible dictionary and when you set ret...
Ansible
40,235,550
23
I need to create or overwrite files on remote hosts. The modules lineinfile or blockinfile are useful when updating files, but not to create ones from scratch or completely overwrite existing ones. The obvious solution is to use copy but I would like to have as much as possible a standalone playbook, without files on t...
Copy with content: tasks: - copy: content: | This is some not too complex cotent for a file dest: content.txt But as per Ansible doc: This is for simple values, for anything complex or with formatting please switch to the template module.
Ansible
38,479,423
23
What is the difference between Ansible template module and Ansible copy module?
While very similar, template serves an extra function. copy takes a file from host, "as-is", and copies it to the remote destination. template takes a file (template) from host, changes variables based on Jinja2 filtering, and copies it to the remote destination. You could use template to copy a file without template...
Ansible
37,675,262
23
How to run Ansible without hosts file? just like: $ ansible --"Some Options" IP -a 'uptime'
you can do like this: ansible all -i "<hostname-or-ip>," -a 'uptime' Note the , at the end of the IP address, or it will be considered a hosts inventory filename. Here is an example for reference: ansible all -i "192.168.33.100," -a 'uptime' 192.168.33.100 | SUCCESS | rc=0 >> 12:05:10 up 10 min, 1 user, load avera...
Ansible
37,652,464
23
I'm working on a role that only needs to gather a single fact. Performance it's a concern and I know that gathering facts it's time-consuming. I'm looking for some way to filter gather_facts inside a playbook, this will allow me to gather only the required facts. This is possible using the setup core module: ansible ...
Yes, that's possible, but not in the default behavior of gathering facts. Having set gather_facts to true simply calls the setup module as very first task of the play. This way you do not have any way to parameterize the setup module call. But you can disable the default behavior and call setup yourself with the filter...
Ansible
34,485,286
23
How can an Ansible playbook register in a variable the result of including another playbook? For example, would the following register the result of executing tasks/foo.yml in result_of_foo? tasks: - include: tasks/foo.yml - register: result_of_foo How else can Ansible record the result of a task sequence?
The short answer is that this can't be done. The register statement is used to store the output of a single task into a variable. The exact contents of the registered variable can vary widely depending on the type of task (for example a shell task will include stdout & stderr output from the command you run in the reg...
Ansible
33,701,062
23
HI i am new to jinja2 and trying to use regular expression as shown below {% if ansible_hostname == 'uat' %} {% set server = 'thinkingmonster.com' %} {% else %} {% set server = 'define yourself' %} {% endif %} {% if {{ server }} match('*thinking*') %} {% set ssl_certificate = 'akash' %} {% elif {{ server }} ...
Jinja2 can quite easily do substr checks with a simple 'in' comparison, e.g. {% set server = 'www.thinkingmonster.com' %} {% if 'thinking' in server %} do something... {% endif %} So your substring regex filter isn't required. However if you want more advanced regex matching, then there are in fact filters availab...
Ansible
30,413,616
23
I am trying to create a task in ansible which executes a shell command to run an executable in daemon mode using &. Something like following -name: Start daemon shell: myexeprogram arg1 arg2 & What am seeing is if I keep & the task returns immediately and the process is not started . If I remove & ansible task wait...
Running program with '&' does not make program a daemon, it just runs in background. To make a "true daemon" your program should do steps described here. If your program is written in C, you can call daemon() function, which will do it for you. Then you can start your program even without '&' at the end and it will be ...
Ansible
29,806,673
23
I need to set up Apache/mod_wsgi in Centos 6.5 so my main YAML file is as such: --- - hosts: dev tasks: - name: Updates yum installed packages yum: name=* state=latest - hosts: dev roles: - { role: apache } This should update all yum-installed packages then execute the apache role. The apache role ...
Well, to answer my own question, I realized that there's a subtle point I missed: http://docs.ansible.com/playbooks_intro.html#handlers-running-operations-on-change Specifically, the notify signal is produced only if the task introduces a change. So for my use case I think I'll go with enabling and starting Apache in s...
Ansible
24,732,627
23
I try to write the playbook.yml for my vagrant machine and I'm faced with the following problem. Ansible prompt me to set these variables and I set these variables to null/false/no/[just enter], but the roles is executed no matter! How can I prevent this behavior? I just want no actions if no vars are set.. --- - name:...
I believe the variables will always be defined when you use vars_prompt, so "is defined" will always be true. What you probably want is something along these lines: - name: Deploy Webserver hosts: webservers vars_prompt: - name: run_common prompt: "Product release version" default: "Y" roles: ...
Ansible
21,063,159
23
If I run apt, I can update the package cache: apt: name: postgresql state: present update_cache: yes I'm now trying to use the generic package command, but I don't see a way to do this. package: name: postgresql state: present Do I have to run an explicit command to run apt-get update, or can I do this usi...
This is not possible. The module package as of writing is just capable to handle package presence, so you have to use directly the package module to refresh the cache.
Ansible
49,087,220
22
I'm looking for an appropriate Ansible Role or Ansible YAML file for installing NodeJS LTS on a Ubuntu 16.04.3 xenial system. I tried more than 10 Ansible roles from Galaxy but didn't find any of them working (throws error such as potentially dangerous to add this PPA etc.. Can anyone provide any Ansible playbook or su...
Here is the working example: --- - hosts: all gather_facts: yes become: yes vars: NODEJS_VERSION: "8" tasks: - name: Install the gpg key for nodejs LTS apt_key: url: "https://deb.nodesource.com/gpgkey/nodesource.gpg.key" state: present - name: Install the nodejs LTS repos ...
Ansible
45,840,664
22
I am trying to setup a Django project in vagrant using ansible. I have used the following code for installing the pip packages: - name: Setup Virtualenv pip: virtualenv={{ virtualenv_path }} virtualenv_python=python3 requirements={{ virtualenv_path }}/requirements.txt I need to use python3 for the django project and...
Had the same issue. There is workaround with usage executable: - name: Install and upgrade pip pip: name: pip extra_args: --upgrade executable: pip3
Ansible
44,455,240
22
I have two variables: a, b. I want to assign a value to a variable c based on which: a or b contains greater numerical value. This what I tried: - set_fact: c: "test1" when: a <= b - set_fact: c: "test2" when: b <= a Look like it always sets c to test1 not test2.
Using if-else expression: - set_fact: c: "{{ 'test1' if (a >= b) else 'test2' }}" Using ternary operator: - set_fact: c: "{{ (a >= b) | ternary ('test1', 'test2') }}" Using your own code which is correct (see the notice below) Either of the above methods requires both variables used in comparison to be of ...
Ansible
42,660,653
22
I believe the Ansible copy module can take a whole bunch of "files" and copy them in one hit. This I believe can be achieved by copying a directory recursively. Can the Ansible template module take a whole bunch of "templates" and deploy them in one hit? Is there such a thing as deploying a folder of templates and appl...
The template module itself runs the action on a single file, but you can use with_filetree to loop recursively over a specified path: - name: Ensure directory structure exists ansible.builtin.file: path: '{{ templates_destination }}/{{ item.path }}' state: directory with_community.general.filetree: '{{ temp...
Ansible
41,667,864
22
I have the following role in my Ansible playbook to determine the installed version of Packer and conditionally install it if it doesn't match the version of a local variable: --- # detect packer version - name: determine packer version shell: /usr/local/bin/packer -v || true register: packer_installed_version ...
From the Ansible docs: Overriding The Changed Result New in version 1.3. When a shell/command or other module runs it will typically report “changed” status based on whether it thinks it affected machine state. Sometimes you will know, based on the return code or output that it did not make any changes, and wish to ov...
Ansible
37,057,086
22
I'm using Ansible to add a user to a variety of servers. Some of the servers have different UNIX groups defined. I'd like to find a way for Ansible to check for the existence of a group that I specify, and if that group exists, add it to a User's secondary groups list (but ignore the statement it if the group does not...
The getent module can be used to read /etc/group - name: Determine available groups getent: database: group - name: Add additional groups to user user: name="{{user}}" groups="{{item}}" append=yes when: item in ansible_facts.getent_group with_items: - sudo - wheel
Ansible
35,807,868
22
I have a playbook that is running in different way in Ansible 1.9.x and 2.0. I would like to check currently running ansible version in my playbook to avoid someone running it with old one. I don't think that this is the best solution: - local_action: command ansible --version register: version What would you sugg...
Ansible provides a global dict called ansible_version, dict contains the following "ansible_version": { "full": "2.7.4", "major": 2, "minor": 7, "revision": 4, "string": "2.7.4" } you can use any of the following ansible_version.full, ansible_version.major or any other c...
Ansible
34,809,845
22
What are the pros and cons to using Ansible Synchronize vs Copy modules. As far as I can tell synchronize has all the functionality that copy does but may be much faster so I'm considering changing everything to use synchronize. The only downside of synchronize is that rsync is required, which seems fairly ubiquitous...
The differences are pretty similar to traditional rsync vs scp. Rsync has more features and is often faster, however it's a little bit trickier to setup and has more knobs to turn. Additionally, https://docs.ansible.com/ansible/copy_module.html states: The “copy” module recursively copy facility does not scale to lots...
Ansible
32,468,350
22
In my Ansible script, I want to generate UUIDs on the fly and use them later on. Here is my approach: - shell: echo uuidgen with_sequence: count=5 register: uuid_list - uri: url: http://www.myapi.com method: POST body: "{{ item.item.stdout }}" with_items: uuid_list.result However I get t...
In ansible 1.9 there is a new filter : to_uuid , which given a string it will return an ansible domain specific UUID,you can find the usage in here https://docs.ansible.com/playbooks_filters.html#other-useful-filters
Ansible
30,516,011
22