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'm trying to create an AWS ECS task with Terraform which will put logs in a specific log group on CloudWatch. The problem is that container definition is in the JSON file and there is no way for me to map the CloudWatch group name from .tf file to that .json file.
container_definition.json:
[
{
"name": "supreme-... | Solved by following @ydaetskcorR's comment.
Made container definition as inline parameter.
container_definitions = <<DEFINITION
[
{
"name": "${var.repository_name}",
"image": "${var.repository_uri}",
"essential": true,
"portMappings": [
{
"containerPort": ... | Terraform | 59,684,900 | 19 |
I want to create a secret in several k8s clusters in the Google Kubernetes Engine using the Terraform.
I know that I can use "host", "token" and some else parameters in "kubernetes" provider, but I can describe these parameters only once, and I don’t know how to connect to another cluster during the file of terraform.... | You can use alias for provider in terraform like described in documentation
So you can define multiple providers for multiple k8s clusters and then refer them by alias.
e.g.
provider "kubernetes" {
config_context_auth_info = "ops1"
config_context_cluster = "mycluster1"
alias = "cluster1"
}
provider "kubernetes... | Terraform | 57,861,264 | 19 |
As a follow up to Terraform 0.12 nested for loops. I am trying to produce an object out of a nested loop but failing miserably :(
How would you go about producing:
Outputs:
association-list = {
"policy1" = "user1"
"policy2" = "user1"
"policy2" = "user2"
}
From:
iam-policy-users-map = {
"policy1" =... | A partial answer can be found at https://github.com/hashicorp/terraform/issues/22263.
Long story short: this was a foolish attempt to begin with, a map cannot contain duplicate keys.
I am however still interested in understanding how a map of maps could be produced from a nested for loop. See second code example above,... | Terraform | 57,280,623 | 19 |
The timestamp() function in the interpolation syntax will return an ISO 8601 formatted string, which looks like this 2019-02-06T23:22:28Z. However, I want to have a string which looks like this 20190206232240706500000001. A string with only numbers (integers) and no hyphens, white spaces, colon, Z or T. What is a simp... | Terraform 0.12.0 introduced a new function formatdate which can make this more readable:
output "timestamp" {
value = formatdate("YYYYMMDDhhmmss", timestamp())
}
At the time of writing, formatdate's smallest supported unit is whole seconds, so this won't give exactly the same result as the regexp approach, but can w... | Terraform | 54,564,512 | 19 |
I have the following simple setup:
~$ tree
.
├── main.tf
└── modules
└── world
└── main.tf
~$ cat main.tf
output "root_module_says" {
value = "hello from root module"
}
module "world" {
source = "modules/world"
}
~$ cat modules/world/main.tf
output "world_module_says" {
value = "hello from world... | Terraform only shows the output from root (by default pre v0.12)
https://www.terraform.io/docs/commands/output.html
Prior to Terraform 0.12 you can get the output from the world module with:
terraform output -module=world
I think the logic here is that the output from the module would be consumed by root and if you ac... | Terraform | 52,503,528 | 19 |
I want to create a S3 and make it encryption at rest with AES256, but terraform complain that: * aws_s3_bucket.s3: : invalid or unknown key: server_side_encryption_configuration (see my code complained by terraform below)
What is wrong with server_side_encryption_configuration? isn't it supported? https://www.terraform... | You probably have an older version of the AWS provider plugin. To update it, run terraform init with the -upgrade flag set to true
terraform init -upgrade=true
| Terraform | 47,957,225 | 19 |
Im using terraform to get the official centos ami:
data "aws_ami" "centos" {
most_recent = true
owners = ["679593333241"] # Centos.org
filter {
name = "name"
values = ["CentOS Linux 7 x86_64 HVM EBS 1708_01-*"]
}
}
I need the owner ID and the way I found it in this case was to aimlessly google until ... | You don't necessarily need the owner ID but it is obviously a good idea to include to ensure you are getting the AMI you expect.
Given that you know the trusted owner up-front, the simple way to find the owner ID is to look in the AMIs table in the AWS console.
From the AWS console, navigate to EC2 > Images > AMIs. Sel... | Terraform | 47,467,593 | 19 |
I'm using the HTTP data source to retrieve data from an internal service. The service returns JSON data.
I can't interpolate the returned JSON data and look up data in it.
For example:
module A
data "http" "json_data" {
url = "http://myservice/jsondata"
# Optional request headers
request_headers {
"... | variable "json" {
default = "{\"foo\": \"bar\"}"
}
data "external" "json" {
program = ["echo", "${var.json}"]
}
output "map" {
value = "${data.external.json.result}"
}
| Terraform | 46,371,424 | 19 |
I have an AWS Auto-Scaling Group, a Launch Configuration, and an Auto-Scaling Group Policy defined in Terraform like this:
resource "aws_autoscaling_group" "default" {
name = "..."
health_check_type = "EC2"
vpc_zone_identifier = ["${...}"]
min_size = "${var.asg_capacity}"
max_size = "${var.asg_capacity * 2}... |
I would assume that this would cause the auto-scaling group to scale up by var.asg_capacity instances, wait 300 seconds, and then tear down the old ones as per OldestInstance.
This assumption, unfortunately, is incorrect. When you change the launch configuration, the only thing that happens is a new launch configurat... | Terraform | 40,985,151 | 19 |
I have used the following code:
module "instance" {
for_each = var.worker_private_ip
source = "../../modules/ec2"
env = var.env
project_name = var.project_name
ami = var.ami
instance_type = var.instance_type
subnet_id ... | From the docs:
path.module is the filesystem path of the module where the expression is placed.
This means that it will return the relative path between your project's root folder and the location where path.module is used.
For example:
if you are using it in a .tf file which is inside your ../../modules/ec2/ folder... | Terraform | 72,480,751 | 18 |
After upgrading terraform to 3.64.2, even though I haven't changed any code, terraform plan reminds me that it will replace tag with tag_all. what's the difference between tags and tags_all?
~ resource "aws_lb_listener" "frontend_http_tcp" {
id = "xxxxx"
~ tags = {
- ... | In Terraform, you can define tags in top-level. tags_all is basically individual resource tags + top level tags
For example;
# Terraform 0.12 and later syntax
provider "aws" {
# ... other configuration ...
default_tags {
tags = {
Environment = "Production"
Owner = "Ops"
}
}
}
resource "... | Terraform | 71,643,844 | 18 |
I'm trying to replicate a SQL instance in GCP via terraform. The active instance has a public IP, however subnets from a secondary project are shared with the project hosing the SQL instance, and the SQL instance is associated with the secondary project's network.
I've added the private_network setting properly (I thin... | If you see the following error:
Error: Error, failed to create instance xxxx: googleapi: Error 400:
Invalid request: Incorrect Service Networking config for instance:
xxxx:xxxxx:SERVICE_NETWORKING_NOT_ENABLED., invalid
Enable the Service Networking API:
gcloud services enable servicenetworking.googleapis.com --projec... | Terraform | 66,536,427 | 18 |
I need to enable "CloudWatch Lambda Insights" for a lambda using Terraform, but could not find the documentation. How I can do it in Terraform?
Note: This question How to add CloudWatch Lambda Insights to serverless config? may be relevant.
| There is no "boolean switch" in the aws_lambda_function resource of the AWS Terraform provider that you can set to true, that would enable Cloudwatch Lambda Insights.
Fortunately, it is possible to do this yourself. The following Terraform definitions are based on this AWS documentation: Using the AWS CLI to enable Lam... | Terraform | 65,735,878 | 18 |
I am trying to get the vpc_id of default vpc in my aws account using terraform
This is what I tried but it gives an error
Error: Invalid data source
this is what I tried:
data "aws_default_vpc" "default" {
}
# vpc
resource "aws_vpc" "kubernetes-vpc" {
cidr_block = "${var.vpc_cidr_block}"
enable_dns_hostnames =... | The aws_default_vpc is indeed not a valid data source. But the aws_vpc data source does have a boolean default you can use to choose the default vpc:
data "aws_vpc" "default" {
default = true
}
| Terraform | 60,619,873 | 18 |
I can select an event from event template when I trigger a lambda function. How can I create a customized event template in terraform. I want to make it easier for developers to trigger the lambda by selecting this customized event template from the list.
I'd like to add an event on this list:
| Unfortunately, at the time of this answer (2020-02-21), there is no way to accomplish this via the APIs that AWS provides. Ergo, the terraform provider does not have the ability to accomplish this (it's limited to what's available in the APIs).
I also have wanted to be able to configure test events via terraform.
A cou... | Terraform | 60,329,800 | 18 |
Following terraform best practice for bootstrapping instances, I'm working on a cloud-init config in order to bootstrap my instance. My only need is to install a specific package.
My terraform config looks like this:
resource "google_compute_instance" "bastion" {
name = "my-first-instance"
machine_type = "n... | cloud-init is installed on the latest (at the moment of writing) Ubuntu 18.04 LTS (ubuntu-1804-bionic-v20191002) image :
<my_user>@instance-1:~$ cat /etc/lsb-release
DISTRIB_ID=Ubuntu
DISTRIB_RELEASE=18.04
DISTRIB_CODENAME=bionic
DISTRIB_DESCRIPTION="Ubuntu 18.04.3 LTS"
<my_user>@instance-1:~$ which cloud-init
/usr/bi... | Terraform | 58,248,190 | 18 |
Lots of examples exist online that show how to run a startup script on a VM deployed on GCP/GCE with Terraform, but they all use inline startup scripts, with all the startup script code included in the terraform compute.tf file. This is done either with a single line for the startup script, or with <<SCRIPT[script code... | To reference a file in your GCE VM declarations just use the file function to read the contents from your selected file. For example:
resource "google_compute_instance" "default" {
...
metadata_startup_script = file("/path/to/your/file")
}
On a similar note, you can also use the template_file data source to perfor... | Terraform | 57,682,483 | 18 |
What I need is terraform analog for CloudFormation's DeletionPolicy: Retain.
The resource should be left as is during terraform destroy, that's all.
prevent_destroy does not fit because the whole environment going to be deleted during terraform destroy
ignore_changes does not fit because there's no parameter's change.
... | You could break down the destroy to a set of tasks
Use terraform state rm, to remove resources/modules you want to retain, from your state. Now they are no longer tracked by terraform.
Remove these resources/modules, from your .tf files
Run terraform plan. You should see that there are no changes to be applied. This i... | Terraform | 56,884,305 | 18 |
In an existing Terraform directory:
~ terraform version
Terraform v0.11.11
+ provider.aws v1.51.0
If I setup a new Terraform directory:
~ terraform version
Terraform v0.11.11
+ provider.aws v1.55.0
How do I upgrade my provider.aws? If I set version = "~> 1.55.0" in the provider "aws" in my .tf file, I get an error:... | terraform init -upgrade
Use terraform init -upgrade command to upgrade the latest acceptable version of each provider.
Before Upgrade
ubuntu@staging-docker:~/terraform$ terraform -version
Terraform v0.12.8
+ provider.aws v2.16.0
+ provider.template v2.1.2
Command to upgrade
ubuntu@staging-docker:~/terraform$ terraform... | Terraform | 54,155,036 | 18 |
I have a terraform module that provisions resources primarily in eu-west-1. I need an ACM certificate to attach to a Cloudfront distribution. The certificate must be provisioned in us-east-1.
I have thus configured two providers:
provider "aws" {
version = "~> 1.0"
region = "eu-west-1"
}
provider "aws" {
version... | Turns out my problem was with aws_acm_certificate_validation. By specifying the provider in the same region as the certificate, it was all resolved.
resource "aws_acm_certificate_validation" "cert" {
provider = "aws.us-east-1" # <== Add this
certificate_arn = "${aws_acm_certificate.cert.arn}"
validation_record_fq... | Terraform | 51,988,417 | 18 |
When creating an AWS Lambda Function with terraform 0.9.3, I'm failing to make it join my selected VPC.
This is how my function looks like:
resource "aws_lambda_function" "lambda_function" {
s3_bucket = "${var.s3_bucket}"
s3_key = "${var.s3_key}"
function_name = "${var.function_name}"
ro... | I think the value of subnet_ids is like this: "subnet-xxxxx,subnet-yyyyy,subnet-zzzzz" and it take it as single subnet instead of list. You can fix this problem like this:
vpc_config {
subnet_ids = ["${split(",", var.subnet_ids)}"]
security_group_ids = ["${var.security_group_ids}"]
}
| Terraform | 43,590,164 | 18 |
I am using Terraform v0.12.26 and set up and aws_alb_target_group as:
resource "aws_alb_target_group" "my-group" {
count = "${length(local.target_groups)}"
name = "${var.namespace}-my-group-${
element(local.target_groups, count.index)
}"
port = 8081
protocol = "HTTP"
vpc_id = var.vpc_id
health... | Since aws_alb_target_group.http is a counted resource you'll need to reference specific instances by index or all of them as a list with [*] (aka Splat Expressions) as follows:
output "target_groups_arn" {
value = aws_alb_target_group.http[*].arn,
}
The target_groups_arn output will be a list of the TG ARNs.
| Terraform | 62,433,708 | 17 |
I have a provisioning pipeline that incorporates Terraform Cloud, and our leadership is asking us to use Terragrunt to improve Terraform code quality.
Terragrunt is a great tool for this, but I haven't see any evidence that anyone has successfully used it on Terraform Cloud.
Can anyone address this? Please only answer ... | Terragrunt expects you to run terragrunt commands, and under the hood, it runs terraform commands, passing along TF_VAR_* environment variables. TFC also runs terraform commands directly. Therefore, you cannot run Terragrunt within TFC - it won't execute the terragrunt binary, only the terraform binary.
However, you ca... | Terraform | 60,062,705 | 17 |
I have a terraform project I am working on. In it, I want a file to contain many variables. I want these variables to be accessible from any module of the project. I have looked in the docs and on a udemy course but still don't see how to do this. How does one do this in terraform? Thanks!
| I don't think this is possible. There are several discussions about this at Github, but this is not something the Hashicorp team wants.
In general we're against the particular solution of Global Variables, since it makes the input -> resources -> output flow of Modules less explicit, and explicitness is a core design ... | Terraform | 59,584,420 | 17 |
This is a bit of a newbie question, but I've just gotten started with GCP provisioning using Terraform / Terragrunt, and I find the workflow with obtaining GCP credentials quite confusing. I've come from using AWS exclusively, where obtaining credentials, and configuring them in the AWS CLI was quite straightforward.
B... |
if I configure Terraform to point to the application_default_credentials.json file, I get the following errors:
The credentials field in provider config expects a path to service account key file, not user account credentials file. If you want to authenticate with your user account try omitting credentials and then r... | Terraform | 57,453,468 | 17 |
I want to allow roles within an account that have a shared prefix to be able to read from an S3 bucket. For example, we have a number of roles named RolePrefix1, RolePrefix2, etc, and may create more of these roles in the future. We want all roles in an account that begin with RolePrefix to be able to access the S3 buc... | You cannot use wildcard along with the ARN in the IAM principal field. You're allowed to use just "*".
https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_principal.html
When you specify users in a Principal element, you cannot use a wildcard (*) to mean "all users". Principals must always nam... | Terraform | 56,678,539 | 17 |
When defining the aws provider in terraform,
provider "aws" {
access_key = "<AWS_ACCESS_KEY>"
secret_key = "<AWS_SECRET_KEY>"
region = "<AWS_REGION>"
}
I'd like to be able to just use the, already defined, system variables
AWS_ACCESS_KEY_ID
AWS_SECRET_ACCESS_KEY
Is there any way to have the tf files read ... | Yes, can read environment variables in Terraform. There is a very specific way that this has to be done. You will need to make the environment variable a variable in terraform.
For example I want to pass in a super_secret_variable to terraform. I will need to create a variable for it in my terraform file.
variable "sup... | Terraform | 53,330,060 | 17 |
The VPC I'm working on has 3 logical tiers: Web, App and DB. For each tier there is one subnet in each availability zone. Total of 6 subnets in the region I'm using.
I'm trying to create EC2 instances using a module and the count parameter but I don't know how to tell terraform to use the two subnets of the App tier. A... | It is possible to evenly distribute instances across multiple zones using modulo.
variable "zone" {
description = "for single zone deployment"
default = "europe-west4-b"
}
variable "zones" {
description = "for multi zone deployment"
default = ["europe-west4-b", "europe-west4-c"]
}
resource "google_compute_ins... | Terraform | 46,041,396 | 17 |
In the terraform docs it shows how to use a template. Is there any way to log this rendered output the console?
https://www.terraform.io/docs/configuration/interpolation.html#templates
data "template_file" "example" {
template = "${hello} ${world}!"
vars {
hello = "goodnight"
world = "moon"
}
}
output "r... | You need to run terraform apply then terraform output rendered
$ terraform apply
template_file.example: Creating...
rendered: "" => "<computed>"
template: "" => "${hello} ${world}!"
vars.#: "" => "2"
vars.hello: "" => "goodnight"
vars.world: "" => "moon"
template_file.example: Creation complete... | Terraform | 37,887,888 | 17 |
I have multiple tasks in a role as follows. I do not want to create another yml file to handle this task. I already have an include for the web servers, but a couple of our Perl servers require some web packages to be installed.
- name: Install Perl Modules
command: <command>
with_dict: perl_modules
- name: Instal... | Below should do the trick:
- name: Install PHP Modules
command: <command>
with_dict: php_modules
when: "'batch' in inventory_hostname"
Note you'll have a couple of skipped hosts during playbook run.
inventory_hostname is one of Ansible's "magic" variables:
Additionally, inventory_hostname is the name of the hos... | Ansible | 30,533,372 | 35 |
In my local.yml I'm able to run the playbook and reference variables within group_vars/all however I'm not able to access variables within group_vars/phl-stage. Let's assume the following.
ansible-playbook -i phl-stage site.yml
I have a variable, let's call it deploy_path that's different for each environment. I place... | You're confusing the structure a bit.
The group_vars directory contains files for each hostgroup defined in your inventory file. The files define variables that member hosts can use.
The inventory file doesn't reside in the group_vars dir, it should be outside.
Only hosts that are members of a group can use its variab... | Ansible | 23,767,765 | 35 |
In ansible playbook I need to run docker-compose commands. How can I do it? I need to run command: docker-compose -f docker-compose.yml -f docker-compose.prod.yml up
| Updated answer 02/2024:
docker_compose_v2 is out since community.docker v3.6.0.
You can copy docker-compose.yml and run Compose such as:
- name: copy Docker Compose files
copy:
src: files/{{ item }}
dest: /somewhere/yourproject/{{ item }}
loop:
- docker-compose.yml
- docker-compose.prod.yml
# use files... | Ansible | 62,452,039 | 34 |
I am running myserver in ubuntu:
+ sudo cat /etc/os-release
NAME="Ubuntu"
VERSION="16.04.6 LTS (Xenial Xerus)"
ID=ubuntu
ID_LIKE=debian
PRETTY_NAME="Ubuntu 16.04.6 LTS"
VERSION_ID="16.04"
HOME_URL="http://www.ubuntu.com/"
SUPPORT_URL="http://help.ubuntu.com/"
BUG_REPORT_URL="http://bugs.launchpad.net/ubuntu/"
VERSION_C... | It appears that you don't have the docker module installed.
You will need to install it via your system package manager (apt install python-docker, for example), or using pip (pip install docker).
If you have multiple Python versions, make sure that you've installed the docker module into the version that Ansible is us... | Ansible | 59,384,708 | 34 |
I'm using Ansible to automate some configuration steps for my application VM, but having difficult to insert a new key-value to an existing json file on the remote host.
Say I have this json file:
{
"foo": "bar"
}
And I want to insert a new key value pair to make the file become:
{
"foo": "bar",
"hello": "world"... | since the file is of json format, you could import the file to a variable, append the extra key:value pairs you want, and then write back to the filesystem.
here is a way to do it:
---
- hosts: localhost
connection: local
gather_facts: false
vars:
tasks:
- name: load var from file
include_vars:
fil... | Ansible | 50,796,341 | 34 |
I'm trying to get the number of hosts of a certain group.
Imagine an inventory file like this:
[maingroup]
server-[01:05]
Now in my playbook I would like to get the number of hosts that are part of maingroup which would be 5 in this case and store that in a variable which is supposed to be used in a template in one ... | vars:
HOST_COUNT: "{{ groups['maingroup'] | length }}"
| Ansible | 36,310,633 | 34 |
I have created a script to start/stop my application. Now I want to add it as a centos system service. First I created a task to create a link from my script to /etc/init.d/service_name as below.
---
- name: create startup link
file: src={{ cooltoo_service_script }} dest={{ cooltoo_service_init }} state=link
After ... | The below code snippet will create Service in CentOS 7.
Code
Tasks
/tasks/main.yml
- name: TeamCity | Create environment file
template: src=teamcity.env.j2 dest=/etc/sysconfig/teamcity
- name: TeamCity | Create Unit file
template: src=teamcity.service.j2 dest=/lib/systemd/system/teamcity.service mode=644
notify:
... | Ansible | 35,984,151 | 34 |
I have templates for configuration files stored in my project's repositories. What I would like to do is use Ansible's template module to create a configuration file using that template on the remote server, after the project has been cloned from the repository.
Looking at the documentation for the template module it a... | You've got two options here if your template is going to be on the remote host.
Firstly, you can use the fetch module which works as pretty much the opposite to the copy module to bring the template back after cloning the repo on the remote host.
A playbook for this might look something like:
- name : clone repo on rem... | Ansible | 33,163,204 | 34 |
I'm starting out with ansible and I'm looking for a way to create a boilerplate project on the server and on the local environment with ansible playbooks.
I want to use ansible templates locally to create some generic files.
But how would i take ansible to execute something locally?
I read something with local_action b... | You can delegate tasks with the parameter delegate_to to any host you like, for example:
- name: create some file
template: src=~/workspace/ansible_templates/somefile_template.j2 dest=/etc/somefile/apps-available/someproject.ini
delegate_to: localhost
See Playbook Delegation in the docs.
For localhost you addition... | Ansible | 31,383,693 | 34 |
I'm currently writing an Ansible play that follows this general format and is run via a cron job:
pre_tasks:
-Configuration / package installation
tasks:
-Work with installed packages
post_tasks:
-Cleanup / uninstall packages
The problem with the above is that sometimes a command in the tasks section fails, a... | This feature became available in Ansible 2.0:
This is the documentation for the new stanza markers block, rescue, and always.
| Ansible | 23,875,377 | 34 |
I am trying to wget a file from a web server from within an Ansible playbook.
Here is the Ansible snippet:
---
- hosts: all
sudo: true
tasks:
- name: Prepare Install folder
sudo: true
action: shell sudo mkdir -p /tmp/my_install/mysql/ && cd /tmp/my_install/mysql/
- name: Download MySql
sudo: true
... | Don't use shell-module when there is specialized modules available. In your case:
Create directories with file-module:
- name: create project directory {{ common.project_dir }}
file: state=directory path={{ common.project_dir }}
Download files with get_url-module:
- name: download sources
get_url: url={{ opencv.ur... | Ansible | 22,939,775 | 34 |
I already know that if you have long conditionals with and between them you can use lists to split them on multiple lines.
Still, I am not aware of any solution for the case where you have OR between them.
Practical example from real life:
when: ansible_user_dir is not defined or ansible_python is not defined or ansib... | Use the YAML folding operator >
when: >
ansible_user_dir is not defined or
ansible_python is not defined or
ansible_processor_vcpus is not defined
As the ansible documentation states:
Values can span multiple lines using | or >. Spanning multiple lines using a Literal Block Scalar | will include the newlines an... | Ansible | 53,098,493 | 33 |
Assuming the below tasks:
- shell: "some_script.sh"
register: "some_script_result"
- debug:
msg: "Output: {{ some_script_result.stdout_lines }}
I receive the below output:
"msg": "Output: [u'some_value',u'some_value2,u'some_value3]"
How do I get the output to print as?
"msg":
Output:
- some_value
- some_va... | Try this option. You’ll love it.
There's a new YAML callback plugin introduced with Ansible 2.5 — meaning any machine running Ansible 2.5.0 or later can automatically start using this format without installing custom plugins.
To use it, edit your ansible.cfg file (either globally, in /etc/ansible/ansible.cfg, or locall... | Ansible | 50,009,505 | 33 |
I've set up a box with a user david who has sudo privileges. I can ssh into the box and perform sudo operations like apt-get install. When I try to do the same thing using Ansible's "become privilege escalation", I get a permission denied error. So a simple playbook might look like this:
simple_playbook.yml:
---
- name... |
Why am I getting permission denied?
Because APT requires root permissions (see the error: are you root?) and you are running the tasks as david.
Per these settings:
become: true
become_user: david
become_method: sudo
Ansible becomes david using sudo method. It basically runs its Python script with sudo david in fron... | Ansible | 40,983,674 | 33 |
For a role I'm developing I need to verify that the kernel version is greater than a particular version.
I've found the ansible_kernel fact, but is there an easy way to compare this to other versions? I thought I might manually explode the version string on the dots (.) and compare the numbers, but I can't even find a... | There is a version test for it:
{{ ansible_distribution_version is version('12.04', '>=') }}
{{ sample_version_var is version('1.0', operator='lt', strict=True) }}
Prior to Ansible 2.5, all tests were also provided as filters, so, the same was achievable with a filter, named version_compare, but in current versi... | Ansible | 39,779,802 | 33 |
I have Ansible role, for example
---
- name: Deploy app1
include: deploy-app1.yml
when: 'deploy_project == "{{app1}}"'
- name: Deploy app2
include: deploy-app2.yml
when: 'deploy_project == "{{app2}}"'
But I deploy only one app in one role call. When I deploy several apps, I call role several times. But every ... | I'm assuming you don't want to see the skipped tasks in the output while running Ansible.
Set this to false in the ansible.cfg file.
display_skipped_hosts = false
Note. It will still output the name of the task although it will not display "skipped" anymore.
UPDATE: by the way you need to make sure ansible.cfg is in ... | Ansible | 39,189,549 | 33 |
Several of my playbooks have sub-plays structure like this:
- hosts: sites
user: root
tags:
- configuration
tasks:
(...)
- hosts: sites
user: root
tags:
- db
tasks:
(...)
- hosts: sites
user: "{{ site_vars.user }}"
tags:
- app
tasks:
(...)
In Ansible 1.x both admins and developers... | There is an easy mod – turn off facts gathering and call setup explicitly:
- hosts: sites
user: root
tags:
- configuration
gather_facts: no
tasks:
- setup:
(...)
| Ansible | 38,308,871 | 33 |
It seems to me that both tools are used to easily install and automatically configure applications.
However, I've limitedly used Docker and haven't used Ansible at all. So I'm a little confused.
Whenever I search for a comparison between these two technologies, I find details about how to use these technologies in com... | There are many reasons most articles talk about using them together.
Think of Ansible as a way of installing and configuring a machine where you can go back and tweak any individual step of that install and configuration in the future. You can then scale that concept out to many machines as you are able to manage.
A ke... | Ansible | 30,550,378 | 33 |
I'm working in a project, and we use ansible to create a deploy a cluster of servers.
One of the tasks that I've to implement, is to copy a local file to the remote host, only if that file exists locally.
Now I'm trying to solve this problem using this
- hosts: 127.0.0.1
connection: local
tasks:
- name: copy l... | A more comprehensive answer:
If you want to check the existence of a local file before performing some task, here is the comprehensive snippet:
- name: get file stat to be able to perform a check in the following task
local_action: stat path=/path/to/file
register: file
- name: copy file if it exists
copy: src=/... | Ansible | 28,855,236 | 33 |
Recently I have been using ansible for a wide variety of automation. However, during testing for automatic tomcat6 restart on specific webserver boxes. I came across this new error that I can't seem to fix.
FAILED => failed to transfer file to /command
Looking at documentation said its because of sftp-server not bein... | do you have sftp subsystem enabled in sshd on the remote server?
You can check it in /etc/sshd/sshd_config, the config file name depends on your distribution…anyway, look there for:
Subsystem sftp /usr/lib/ssh/sftp-server
If this line is commented-out, the sftp is disabled.
To fix it, you can either enable sft... | Ansible | 23,899,028 | 33 |
For a backup I need to iterate over all hosts in my inventory file to be sure that the backup destination exists. My structure looks like
/var/backups/
example.com/
sub.example.com/
So I need a (built-in) variable/method to list all hosts from inventory file, not only a single group.
For groups... | Thats the solution:
with_items: groups['all']
| Ansible | 20,828,703 | 33 |
In Ansible, what is the difference between the service and the systemd modules? The service module seems to include the systemd module so what's the point of having systemd by itself?
| The module service is a generic one. According to the Ansible documentation :
Supported init systems include BSD init, OpenRC, SysV, Solaris SMF, systemd, upstart.
The module systemd is available only from Ansible 2.2 and is dedicated to systemd.
According to the developers of Ansible :
we are moving away from havin... | Ansible | 43,974,099 | 32 |
OVERVIEW
I'd like to have reliable django deployments and I think I'm not following the best practices here. Till now I've been using fabric as a configuration management tool in order to deploy my django sites but I'm not sure that's the best way to go.
In the high performance django book there is a warning which says... |
Does it make sense using both fabric and ansible tools somehow?
Yes. All your logic should live in Ansible and you can use Fabric as a lightweight wrapper around it.
fab deploy
is easier to remember than, e.g.
ansible-playbook -v --inventory=production --tags=app site.yml
Is it possible to use ansible from my windo... | Ansible | 39,370,364 | 32 |
I am working on a role where I want one task to be run at the end of the tasks file if and only if any of the previous tasks in that task file have changed.
For example, I have:
- name: install package
apt: name=mypackage state=latest
- name: modify a file
lineinfile: do stuff
- name: modify a second file
linei... | Best practice here is to use handlers.
In your role create a file handlers/main.yml with the content:
- name: restart mypackage
service: name=mypackage state=restarted
Then notify this handler from all tasks. The handler will be notified only if a task reports a changed state (=yellow output)
- name: install package... | Ansible | 38,144,598 | 32 |
Is there a way to evaluate a relative path in Ansible?
tasks:
- name: Run docker containers
include: tasks/dockerup.yml src_code='..'
Essentially I am interested in passing the source code path to my task. It happens that the source code is the parent path of {{ansible_inventory}} but there doesn't seem to be an... | You can use the dirname filter:
{{ inventory_dir | dirname }}
For reference, see Managing file names and path names in the docs.
| Ansible | 35,271,368 | 32 |
Trying to register an ec2 instance in AWS with Ansible's ec2_ami module, and using current date/time as version (we'll end up making a lot of AMIs in the future).
This is what I have:
- name: Create new AMI
hosts: localhost
connection: local
gather_facts: false
vars:
tasks:
- include_vars: ami_vars.yml
... | Remove this:
gather_facts: false
ansible_date_time is part of the facts and you are not gathering it.
| Ansible | 35,232,088 | 32 |
I am running a custom command because I haven't found a working module doing what I need, and I want to adjust the changed flag to reflect the actual behaviour:
- name: Remove unused images
shell: '[ -n "$(docker images -q -f dangling=true)" ] && docker rmi $(docker images -q -f dangling=true) || echo Ignoring failur... | I think you may have misinterpreted what changed_when does.
changed_when marks the task as changed based on the evaluation of the conditional statement which in your case is:
"command_result.stdout == 'Ignoring failure...'"
So whenever this condition is true, the task will be marked as changed.
| Ansible | 31,731,756 | 32 |
How can I get the current role name in an ansible task yaml file?
I would like to do something like this
---
# role/some-role-name/tasks/main.yml
- name: Create a directory which is called like the current role name
action: file
path=/tmp/"{{ role_name }}"
mode=0755
state=directory
The... | The simplest way is to just use the following
{{role_path|basename}}
| Ansible | 25,324,261 | 32 |
I want to change one line of my code in file /var/www/kibana/config.js during installation from
elasticsearch: "http://"+window.location.hostname+":9200"
to
elasticsearch: "http://192.168.1.200:9200"
Here I tried to use lineinfile to do that as show below
- name: Comment out elasticsearch the config.js to ElasticSear... | The solution that will work in any case no matter how many nested quotes you might have and without forcing you to add more quotes around the whole thing (which can get tricky to impossible depending on the line you want to write) is to output the colon through a Jinja2 expression, which simply returns the colon as a s... | Ansible | 24,835,706 | 32 |
I'm trying to restart the Jenkins service using Ansible:
- name: Restart Jenkins to make the plugin data available
service: name=jenkins state=restarted
- name: Wait for Jenkins to restart
wait_for:
host=localhost
port=8080
delay=20
timeout=300
- name: Install Jenkins plugins
command:
java -... | Using the URI module http://docs.ansible.com/ansible/uri_module.html
- name: "wait for ABC to come up"
uri:
url: "http://127.0.0.1:8080/ABC"
status_code: 200
register: result
until: result.status == 200
retries: 60
delay: 1
| Ansible | 23,919,744 | 32 |
I'm trying to execute my first remote shell script on Ansible. I've first generated and copied the SSH keys. Here is my yml file:
---
- name: Ansible remote shell
hosts: 192.168.10.1
user: myuser1
become: true
become_user: jboss
tasks:
- name: Hello server
shell: /home/jboss/script.sh
When launchin... | You need to define a host inventory.
The default path for this is /etc/ansible/hosts (as also stated by helloV).
For a minimal example you can also specify an inventory in the command line:
ansible-playbook setup.yml -i 192.168.10.1,
The trailing comma makes it a list, such that ansible parses it directy. Otherwise yo... | Ansible | 38,203,317 | 31 |
---
# file: main.yml
- hosts: fotk
remote_user: fakesudo
tasks:
- name: create a developer user
user: name={{ user }}
password={{ password }}
shell=/bin/bash
generate_ssh_key=yes
state=present
roles:
- { role: create_developer_environment, sudo_user: "{{ user }}" }... | You can also do pre_tasks: and post_tasks: if you need to do things before or after. From the Docs https://docs.ansible.com/ansible/latest/user_guide/playbooks_reuse_roles.html
- hosts: localhost
pre_tasks:
- shell: echo 'hello in pre'
roles:
- { role: some_role }
tasks:
- shell: echo 'in tasks'
... | Ansible | 30,987,865 | 31 |
I'm trying to reboot server running CentOS 7 on VirtualBox. I use this task:
- name: Restart server
command: /sbin/reboot
async: 0
poll: 0
ignore_errors: true
Server is rebooted, but I get this error:
TASK: [common | Restart server] ***********************************************
fatal: [rolcabox] => SSH Error... | You're likely not doing anything truly wrong, it's just that /sbin/reboot is shutting down the server so quickly that the server is tearing down the SSH connection used by Ansible before Ansible itself can close it. As a result Ansible is reporting an error because it sees the SSH connection failing for an unexpected r... | Ansible | 29,955,605 | 31 |
I have a problem installing MySQL with ansible on a vagrant ubuntu,
This is my MySQL part
---
- name: Install MySQL
apt:
name: "{{ item }}"
with_items:
- python-mysqldb
- mysql-server
- name: copy .my.cnf file with root password credentials
template:
src: templates/root/.my.cnf
dest: ~/.my.c... | When mysql-server is installed headlessly, there's no password. Therefore to make .my.cnf work, it should have a blank password line. Here's what I tested with for a .my.cnf:
[client]
user=root
password=
It's also slightly strange to put .my.cnf in your vagrant user directory as owned by root and only readable as root... | Ansible | 26,597,926 | 31 |
Ansible expects python 2. On my system (Arch Linux), "python" is Python 3, so I have to pass -e "ansible_python_interpreter=/usr/bin/python2" with every command.
ansible-playbook my-playbook.yml -e "ansible_python_interpreter=/usr/bin/python2"
Is there a away to set ansible_python_interpreter globally on my system, so... | Well you can set in three ways
http://docs.ansible.com/intro_inventory.html#list-of-behavioral-inventory-parameters ansible_python_interpreter=/usr/bin/python2 this will set it per host
Set it host_vars/ ansible_python_interpreter: "/usr/bin/python2" this will set it per host
set it for all nodes in the file group_var... | Ansible | 22,769,568 | 31 |
I am using ansible to replace the ssh keys for a user on multiple RHEL6 & RHEL7 servers. The task I am running is:
- name: private key
copy:
src: /Users/me/Documents/keys/id_rsa
dest: ~/.ssh/
owner: unpriv
group: unpriv
mode: 0600
backup: yes
Two of the hosts that I'm trying to update are... | Try to install ACL on remote host, after that execute ansible script
sudo apt-get install acl
As explained in the doc
when both the connection user and the become_user are unprivileged, the module file is written as the user that Ansible connects as (the remote_user), but the file needs to be readable by the user Ans... | Ansible | 46,352,173 | 30 |
Heres my if else Ansible logic ..
- name: Check certs exist
stat: path=/etc/letsencrypt/live/{{ rootDomain }}/fullchain.pem
register: st
- include: ./_common/check-certs-renewable.yaml
when: st.stat.exists
- include: ./_common/create-certs.yaml
when: not st.stat.exists
This code boils down to:
IF certs exis... | What you have there should work and is one way of doing it.
Alternatively, you could use a Jinja query to reduce it to 2 tasks, such that:
- name: Check certs exist
stat: path=/etc/letsencrypt/live/{{ rootDomain }}/fullchain.pem
register: st
- include: "{{ './_common/check-certs-renewable.yaml' if st.stat.exis... | Ansible | 42,037,814 | 30 |
I've an error when I launch a playbook but I don't found why....
ERROR! the field 'hosts' is required but was not set
There is my main.yml :
---
- hosts: hosts
- vars:
- elasticsearch_java_home: /usr/lib/jmv/jre-1.7.0
- elasticsearch_http_port: 8443
- tasks:
- include: tasks/main.yml
- handlers:
- include... | You have a syntax error in your playbook.
---
- hosts: webservers
vars:
http_port: 80
max_clients: 200
See: https://docs.ansible.com/ansible/latest/playbook_guide/playbooks_intro.html
| Ansible | 36,724,870 | 30 |
I have an ansible 2.1.0 on my server, where I do deployment via vagrant and on PC too.
The role "deploy" have :
- name: upload code
become: true
become_user: www-data
git: repo=git@bitbucket.org:****.git
dest=/var/www/main
key_file=/var/www/.ssh/id_rsa
accept_hostkey=true
update=yes
force... | On debian/ubuntu you can resolve this by first installing the acl package on the remote host, like with this ansible task:
- name: install setfacl support
become: yes
apt: pkg=acl
Same thing with redhat/centos -- install the acl package on the remote host:
- name: install setfacl support
become: yes
yum: name=... | Ansible | 36,646,880 | 30 |
I want to add keys to a dictionary when using set_fact with with_items. This is a small POC which will help me complete some other work. I have tried to generalize the POC so as to remove all the irrelevant details from it.
When I execute following code it is shows a dictionary with only one key that corresponds to the... | This can also be done without resorting to plugins, tested in Ansible 2.2.
---
- hosts: localhost
connection: local
vars:
some_value: 12345
dict: {}
tasks:
- set_fact:
dict: "{{ dict | combine( { item: some_value } ) }}"
with_items:
- 1
- 2
- 3
- debug: msg="{{ dict }}"
Al... | Ansible | 31,772,732 | 30 |
I am downloading the file with wget from ansible.
- name: Download Solr
shell: wget http://mirror.mel.bkb.net.au/pub/apache/lucene/solr/4.7.0/solr-4.7.0.zip
args:
chdir: {{project_root}}/solr
but I only want to do that if zip file does not exist in that location. Currently the system is downloadin... | Note: this answer covers general question of "How can i check the file existence in ansible", not a specific case of downloading file.
The problems with the previous answers using "command" or "shell" actions is that they won't work in --check mode. Actually, first action will be skipped, and next will error out on "wh... | Ansible | 22,469,880 | 30 |
I am working with vagrant and ansible. I want to automate the deployment role of ansible (You can check my repo here).
For this purpose, I am trying to deploy my local ssh key into my VPS and my vagrant guest machine (I am trying SSH agent forwarding).
GOAL
Automate deployment process with git using ansible. I've alrea... | You don't have to copy your local SSH key to remote servers. Instead, you just create file named ansible.cfg in the directory you are running deployment scripts from, and put the next settings:
[ssh_connection]
ssh_args = -o ForwardAgent=yes
That's it, now your local identity is forwarded to the remote servers you man... | Ansible | 21,925,808 | 30 |
Currently I have all of my deployment scripts in shell, which installs about 10 programs and configures them. The way I see it shell is a fantastic tool for this:
Modular: Only one program per script, this way I can spread the programs across different servers.
Simple: Shell scripts are extremely simple and don't need ... | Shell scripts aren't that bad, if you've got them working like you need to.
People recommend other tools (such as CFEngine, Puppet, Chef, Ansible, and whatever else) for various reasons, some of which are:
The same set of reasons why people use tools like make instead of implementing build
systems with scripts.
Idemp... | Ansible | 19,702,879 | 30 |
My local /etc/ansible/hosts file just has
[example]
172.31.nn.nnn
Why do I get that
host_list declined parsing /etc/ansible/hosts as it did not pass it's verify_file() method
message ?
If I change it to
[local]
localhost ansible_connection=local
it seems to work ok.
But that is limited to local. I want to ping my aw... | The messages about declined parsing are informational only. There are several different plugins for inventory files, and you can see from the output that the ini plugin is successfully parsing your inventory (Parsed /etc/ansible/hosts inventory source with ini plugin).
This issue is unrelated to Ansible. You need to fi... | Ansible | 56,465,268 | 29 |
I am new to ansible.
Is there a simple way to replace the line starting with option domain-name-servers in /etc/dhcp/interface-br0.conf with more IPs?
option domain-name-servers 10.116.184.1,10.116.144.1;
I want to add ,10.116.136.1
| You can use the lineinfile Ansible module to achieve that.
- name: replace line
lineinfile:
path: /etc/dhcp/interface-br0.conf
regexp: '^(.*)option domain-name-servers(.*)$'
line: 'option domain-name-servers 10.116.184.1,10.116.144.1,10.116.136.1;'
backrefs: yes
The regexp option tells... | Ansible | 40,788,575 | 29 |
I have the following tasks in a playbook I'm writing (results listed next to the debug statement in <>):
- debug: var=nrpe_installed.stat.exists <true>
- debug: var=force_install <true>
- debug: var=plugins_installed.stat.exists <true>
- name: Run the prep
include: prep.yml
when: (nrpe_installed.stat.... | You need to convert the variable to a boolean:
force_install|bool == true
I don't claim I understand the logic behind it. In python any non-empty string should be truthy. But when directly used in a condition it evaluates to false.
The bool filter then again interprets the strings 'yes', 'on', '1', 'true' (case-insen... | Ansible | 37,888,760 | 29 |
I want to execute the next command using ansible playbook:
curl -X POST -d@mesos-consul.json -H "Content-Type: application/json" http://marathon.service.consul:8080/v2/apps
How can I run it?
If I run:
- name: post to consul
uri:
url: http://marathon.service.consul:8080/v2/apps/
method: POST
body: "{{ loo... | The best way to do this is to use the URI module:
tasks:
- name: post to consul
uri:
url: http://marathon.service.consul:8080/v2/apps/
method: POST
body: "{{ lookup('file','mesos-consul.json') }}"
body_format: json
headers:
Content-Type: "application/json"
Since your json file is on the rem... | Ansible | 35,798,101 | 29 |
My basic problem is that upon creation of a set of aws servers I want to configure them to know about each other.
Upon creation of each server their details are saved in a registered 'servers' var (shown below). What I really want to be able to do after creation is run a task like so:
- name: Add servers details to all... | Jinja2 comes with a built-in filter sum which can be used like:
{{ servers.results | sum(attribute='tagged_instances', start=[]) }}
| Ansible | 31,876,069 | 29 |
Anyone on my team can SSH into our special deploy server, and from there run an Ansible playbook to push new code to machines.
We're worried about what will happen if two people try to do deploys simultaneously. We'd like to make it so that the playbook will fail if anyone else is currently running it.
Any suggestions ... | Personally I use RunDeck ( http://rundeck.org/ ) as a wrapper around my Ansible playbooks for multiple reasons:
You can set a RunDeck 'job' to only be able to be run at one time (or set it to run as many times at the same time as you want)
You can set up users within the system so that auditing of who has run what is ... | Ansible | 21,869,912 | 29 |
I am new to ansible and was exploring dependent roles. documentation link
What I did not come across the documentation was- where to place the requirements.yml file.
For instance, if my site.yml looks like this:
---
- name: prepare system
hosts: all
roles:
- role1
And, lets say
role1 depends on role2 and ro... | Technically speaking, you could put your requirements.yml file anywhere you like as long as you reflect the correct path in your ansible-galaxy install command.
Meanwhile, if you ever want to run your playbooks from Ansible Tower/Awx, I suggest you stick to the Ansible Tower requirements and put your requirements.yml f... | Ansible | 55,773,505 | 28 |
I have a very complex Ansible setup with thousands of servers and hundreds of groups various servers are member of (dynamic inventory file).
Is there any way to easily display all groups that a specific host is member of?
I know how to list all groups and their members:
ansible localhost -m debug -a 'var=groups'
But I... | Create a playbook called 'showgroups' (executable file) containing:
#!/usr/bin/env ansible-playbook
- hosts: all
gather_facts: no
tasks:
- name: show the groups the host(s) are in
debug:
msg: "{{group_names}}"
You can run it like this to show the groups of one particular host (-l) in your inventory (-... | Ansible | 46,362,787 | 28 |
I have to parse the output of the following command:
mongo <dbname> --eval "db.isMaster()"
which gives output as follows:
{
"hosts" : [
"xxx:<port>",
"xxx:<port>",
"xxx:<port>"
],
"setName" : "xxx",
"setVersion" : xxx,
"ismaster" : true,
"secondary" : false,
"primar... | There are quite a bit of helpful filters in Ansible.
Try: when: (output_text.stdout | from_json).ismaster
| Ansible | 40,844,720 | 28 |
I have this Docker image -
FROM centos:7
MAINTAINER Me <me.me>
RUN yum update -y
RUN yum install -y git https://dl.fedoraproject.org/pub/epel/epel-release-latest-7.noarch.rpm
RUN yum install -y ansible
RUN git clone https://github.com/.../dockerAnsible.git
RUN ansible-playbook dockerFileBootstrap.yml
RUN (cd /lib/sys... | You should use supervisor in order to launch several services
In your dockerfile, install supervisor, then you launch
COPY ./docker/supervisord.conf /etc/supervisord.conf
....
CMD ["/usr/bin/supervisord", "-n"]
And your docker/supervisord.conf contains all the services you want to start, so you can have something like... | Ansible | 37,313,780 | 28 |
Ansible 1.9.4.
The script should execute some task only on hosts where some variable is defined. It works fine normally, but it doesn't work with the with_items statement.
- debug: var=symlinks
when: symlinks is defined
- name: Create other symlinks
file: src={{ item.src }} dest={{ item.dest }} state=link
with_i... | with_items: "{{ symlinks | default([]) }}"
| Ansible | 35,470,667 | 28 |
Ansible Best Practices described that every role contains file directory that have all files needed by this rule.
In my case I have different roles that share the same files. But I cannot make a copy of these files in each role as there will be no one source of these files and if edit happens to one of them it will bec... | You've got two reasonably decent approaches you can try here to reduce repetition.
You could have a separate shared-files directory that sits as a sibling to your role folders like this:
play.yml
roles/
web/
tasks/
files/
other-multiple-files
role-2/
tasks/
files/
other-multiple-files
... | Ansible | 34,287,465 | 28 |
I'm trying to create an small webapp infrastructure with ansible on Amazon AWS and I want to do all the process: launch instance, configure services, etc. but I can't find a proper tool or module to deal with that from ansible. Mainly EC2 Launch.
Thanks a lot.
| This is the short answer of your question, if you want detail and fully automated role, please let me know. Thanks
Prerequisite:
Ansible
Python boto library
Set up the AWS access and secret keys in the environment settings
(best is inside the ~./boto)
To Create the EC2 Instance(s):
In order to create the EC2 Instance... | Ansible | 30,227,140 | 28 |
I execute a shell: docker ps ... task in some of my playbooks. This normally works but sometimes the docker daemon hangs and docker ps does not return for ~2 hours.
How can I configure Ansible to timeout in a reasonable amount of time if docker ps does not return?
| A task timeout (in seconds) is added in 2.10 release, which is useful in such scenarios.
https://github.com/ansible/ansible/issues/33180 --> https://github.com/ansible/ansible/pull/69284
Playbook Keywords
For example, below playbook fails in 2.10 version:
---
- hosts: localhost
connection: local
gather_facts: f... | Ansible | 41,947,750 | 27 |
I have the following task in my ansible playbook:
- name: Install EPEL repo.
yum:
name: "{{ epel_repo_url }}"
state: present
register: result
until: '"failed" not in result'
retries: 5
delay: 10
Another value I can pass to state is "installed". What is the difference between the two? Some do... | They do the same thing, i.e. they are aliases to each other, see this comment in the source code of the yum module:
# removed==absent, installed==present, these are accepted as aliases
And how they are used in the code:
if state in ['installed', 'present']:
if disable_gpg_check:
yum_basecmd.append('--nogpgc... | Ansible | 40,410,270 | 27 |
Is it possible to apply a list of items to multiple tasks in an Ansible playbook? To give an example:
- name: download and execute
hosts: server1
tasks:
- get_url: url="some-url/{{item}}" dest="/tmp/{{item}}"
with_items:
- "file1.sh"
- "file2.sh"
- shell: /tmp/{{item}} >> somelog.txt
with_items:... | As of today you can use with_items with include, so you'd need to split your playbook into two files:
- name: download and execute
hosts: server1
tasks:
- include: subtasks.yml file={{item}}
with_items:
- "file1.sh"
- "file2.sh"
and subtasks.yml:
- get_url: url="some-url/{{file}}" dest="/tmp/{{file}}... | Ansible | 39,040,521 | 27 |
Here I am trying to test my bash script where it is prompting four times.
#!/bin/bash
date >/opt/prompt.txt
read -p "enter one: " one
echo $one
echo $one >>/opt/prompt.txt
read -p "enter two: " two
echo $two
echo $two >>/opt/prompt.txt
read -p "enter three: " three
echo $three
echo $three >>/opt/prompt.txt
read -p "ent... | The reason is that the questions are interpreted as regexps. Hence you must escape characters with a special meaning in regular expressions, such as -()[]\?*. et cetara.
Hence:
'Enter current password for root (enter for none):'
should instead be:
'Enter current password for root \(enter for none\):'
Good luck!
| Ansible | 38,393,343 | 27 |
Is it possible to skip some items in Ansible with_items loop operator, on a conditional, without generating an additional step?
Just for example:
- name: test task
command: touch "{{ item.item }}"
with_items:
- { item: "1" }
- { item: "2", when: "test_var is defined" }
- { item: "3" }
in this... | The other answer is close but will skip all items != 2. I don't think that's what you want. here's what I would do:
- hosts: localhost
tasks:
- debug: msg="touch {{item.id}}"
with_items:
- { id: 1 }
- { id: 2 , create: "{{ test_var is defined }}" }
- { id: 3 }
when: item.create | default(True)... | Ansible | 37,189,826 | 27 |
I used an ansible playbook to install git:
---
- hosts: "www"
tasks:
- name: Update apt repo
apt: update_cache=yes
- name: Install dependencies
apt: name={{item}} state=installed
with_items:
- git
I checked the installed versions:
$ git --version
git version 1.9.1
But adding these to the ansib... | Git package with that specific version is as follows:
git=1:1.9.1-1ubuntu0.2
Your task should be:
apt: name=git=1:1.9.1-1ubuntu0.2 state=present
Regards
| Ansible | 36,150,362 | 27 |
I am using the host file as below,
[qa-workstations]
10.39.19.190 ansible_user=test ansible_ssh_pass=test
I am using below command to execute "whoami" command in host
root@Svr:~/ansible# ansible all -a "whoami" -i /etc/ansible/host
10.39.19.190 | success | rc=0 >>
root
ansible by default trying to use user name in wh... | With recent versions of Ansible, you can use the ansible_user parameter in the host definition.
For example, on the host mysql-host.mydomain the user I need to connect with is mysql :
[docker-hosts]
mysql-host.mydomain ansible_user=mysql
But as you are using an older version of ansible, you might need to use ansible_s... | Ansible | 34,334,377 | 27 |
I have a playbook with multiple hosts section. I would like to define a variable in this playbook.yml file that applies only within the file, for example:
vars:
my_global_var: 'hello'
- hosts: db
tasks:
-shell: echo {{my_global_var}}
- hosts: web
tasks:
-shell: echo {{my_global_var}}
The example above ... | The set_fact module will accomplish this if group_vars don't suit your needs.
https://docs.ansible.com/ansible/latest/collections/ansible/builtin/set_fact_module.html
This module allows setting new variables. Variables are set on a host-by-host >basis just like facts discovered by the setup module. These variables wil... | Ansible | 33,992,153 | 27 |
I was given a task to verify some routing entries for all Linux server and here is how I did it using an Ansible playbook
---
- hosts: Linux
serial: 1
tasks:
- name: Check first
command: /sbin/ip route list xxx.xxx.xxx.xxx/24
register: result
changed_when: false
- debug: ... | Starting in Ansible 1.6.1, the results registered with multiple items are stored in result.results as an array. So you can use result.results[0].stdout and so on.
Testing playbook:
---
- hosts: localhost
gather_facts: no
tasks:
- command: "echo {{item}}"
register: result
with_items: [1, 2]
- de... | Ansible | 31,881,762 | 27 |
I have very simple line in the template:
ip={{ip|join(', ')}}
And I have list for ip:
ip:
- 1.1.1.1
- 2.2.2.2
- 3.3.3.3
But application wants IPs with quotes (ip='1.1.1.1', '2.2.2.2').
I can do it like this:
ip:
- "'1.1.1.1'"
- "'2.2.2.2'"
- "'3.3.3.3'"
But it is very ugly. Is any nice way to add quotes on eac... | This will work :
ip={{ '\"' + ip|join('\", \"') + '\"' }}
A custom filter plugin will also work. In ansible.cfg uncomment filter_plugins and give it a path, where we put this
def wrap(list):
return [ '"' + x + '"' for x in list]
class FilterModule(object):
def filters(self):
return {
'wrap... | Ansible | 29,537,684 | 27 |
I'm struggling with a pattern pulling inventory vars in Ansible templates, please help. :)
I'm setting up a monitoring server, and I want to be able to automatically provision the servers using Ansible. I'm struggling with loops in the template to allow me to this.
My semi-working soluition so far is in the playbook th... | Ideally you would be using different inventory files for production and staging, which would allow you to keep the same {{ inventory_hostname }} value, but target different machines.
You can also loop through different groups...
hosts:
[web]
web1
web2
[db]
db1
db2
playbook:
- name: play that sets a group to loop over... | Ansible | 26,989,492 | 27 |
---
- hosts: test
tasks:
- name: print phone details
debug: msg="user {{ item.key }} is {{ item.value.name }} ({{ item.value.telephone }})"
with_dict: "{{ users }}"
vars:
users:
alice: "Alice"
telephone: 123
When I run this playbook, I am getting this error:
One or more undefined va... | This is not the exact same code. If you look carefully at the example, you'll see that under users, you have several dicts.
In your case, you have two dicts but with just one key (alice, or telephone) with respective values of "Alice", 123.
You'd rather do :
- hosts: localhost
gather_facts: no
tasks:
- name: pr... | Ansible | 26,639,325 | 27 |
In a playbook I got the following code:
---
- hosts: db
vars:
postgresql_ext_install_contrib: yes
postgresql_pg_hba_passwd_hosts: ['10.129.181.241/32']
...
I would like to replace the value of postgresql_pg_hba_passwd_hosts with all of my webservers private ips. I understand I can get the values like this in... | You can assign a list to variable by set_fact and ansible filter plugin.
Put custom filter plugin to filter_plugins directory like this:
(ansible top directory)
site.yml
hosts
filter_plugins/
to_group_vars.py
to_group_vars.py convert hostvars into list that selected by group.
from ansible import errors, runner
imp... | Ansible | 24,798,382 | 27 |
I'm new to ansible (and docker). I would like to test my ansible playbook before using it on any staging/production servers.
Since I don't have access to an empty remote server, I thought the easiest way to test would be to use Docker container and then just run my playbook with the Docker container as the host.
I have... | Running the playbook in a docker container may not actually be the best approach unless your stage and production servers are also Docker containers. The Docker ubuntu image is stripped down and will have some differences from a full installation. A better option might be to run the playbook in an Ubuntu VM that matche... | Ansible | 24,738,264 | 27 |
In my playbooks I reference username (exclusively its "ubuntu") a lot.
Is there a built in way to say "get it from the value passed in the command line"?
I know I can do
ansible-playbook <task> -u <user> -K --extra-vars "user=<user>"
and then I can use {{user}} in the playbook, but it feels odd defining the user twice... | As Woodham stated, the ansible variable that represents the connecting user is
{{ ansible_user }} (Ansible < 2.0 was {{ ansible_ssh_user }} )
But you don't have to define it in the inventory file per se.
You can define it in:
1. Your play, if you use ansible-playbook:
See the manual on Playbooks
- name: Some play
ho... | Ansible | 24,095,807 | 27 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.