Ansible - how to concatenate files contents into a variable

How can I concatenate a contents of several files into a variable? Here's the problem: I'm trying to set public keys for a user on a remote machine. The example from the authorized_key documentation that almost works: - name: Set up authorized_keys for the deploy user authorized_key: user=deploy key="{{ item }}" with_file: - public_keys/doe-jane - public_keys/doe-john But in fact I need to use exclusive=yes, so after the update all non-provided public keys are r

Ansible module: ec2_elb unable to find ELB (when ELB count>400?)

I have EC2 instances that needs to be added to an ELB. While trying this from ansible, getting the following error. I am able to add the same using AWS CLI. Found this open issue with the module ec2_elb in ansible: Is there any work around for this? Or any other version of boto/python where this works as expected. I do have >400 ELB's in the profile that i am using. msg: ELB MyTestELB does not exist.

Ansible How to read and manipulate settings based on an acronym

What strategy you use to control custom settings? Using ini files or save files in yaml format ?! For example I have settings for acronym of my establishment. How do I access from my playbook these variables or custom data? I want to read the settings conditionally. Based on the referenced acronym. Like that: ansible-playbook -i hosts myplaybooy.yml my_acronym Example structure where CAX, BAC and SIN are acronyms: CAX IP_SERVER = IP_DB_MASTER = IP_DB_SLAVE =

Ansible for download the files from FTP

Currently, I'm using shell script to download the files from FTP server. Ansible will execute my script and continue other automated jobs. Please let me know the best way to do this in Ansible playbook using "get_url" instead of "shell". The following syntax is working only to download the single file but my requirements are to download the multiple files and directories. Appreciated your help. - name: FTP Download get_url: url=

Ansible - playbook calls another playbook with variables, tags, and limits

I have a blue green deploy playbook. It relies on certain variables to determine which hosts to apply the underlying roles. Here is one of the roles for an example: - name: Remove current server from load balancer hosts: 'tag_Name_{{server_name}}_production' remote_user: ec2-user sudo: true roles: - remove-load-balancer I can call this playbook with specified limits and tags and it works wonderfully - but only for one type of server. For example, this command will blue green deplo

Short version of if var is defined for ansible templates

Jinja2 in Ansible templates allows this type of expression in templates: {% if foobar is defined %} foo_bar = {{foobar}} {% endif %} {% if barfoo is defined %} bar_foo = {{barfoo}} {% endif %} etc. Is there any shorter version to say 'do not print this line if its variable is not defined? Something like foo_bar = {{foobar|skip_this_line_if_undefined}}?

Deleting multiple files in most efficient way (ansible)

I want to delete couple of files, right now I do it this way: - file: path=/etc/yum.repos.d/rhel6-6-hci-frozen.repo state=absent name: Ensure absence of old freeze files - file: path=/etc/yum.repos.d/in-mrepo-rhel6.repo state=absent name: Ensure absence of old files ... many other lines The problem with this is that ansible seems to execute these one by one, instead of merging it into one task: TASK [Ensure absence of old freeze files] ************************************** changed: [s

Accessing inventory host variable in Ansible playbook

In Ansible 2.1, I have a role being called by a playbook that needs access to a host file variable. Any thoughts on how to access it? I am trying to access the ansible_ssh_host in the test1 section of the following inventory host file: [test1] test-1 ansible_ssh_host=abc.def.ghi.jkl ansible_ssh_port=1212 [test2] test2-1 ansible_ssh_host=abc.def.ghi.mno ansible_ssh_port=1212 [test3] test3-1 ansible_ssh_host=abc.def.ghi.pqr ansible_ssh_port=1212 test3-2 ansible_ssh_host=abc.def.ghi.stu ansible_

Trouble running Ansible external module

I'm trying to use the Jboss Module in a playbook. As per example: # Deploy a hello world application - jboss: src: /tmp/hello-1.0-SNAPSHOT.war deployment: hello.war state: present However it seems the jboss module is not recognized: The offending line appears to be: - jboss: ^ here I've copied the module (from in the folder defined by: library = /home/jboss/ansible/lib

linking against openssl 1.0.0 when run ansible-playbook

after installed ansible on a redhat linux machine(kernel version unknown) when run ansible-playbook I got such error. RuntimeError: You are linking against OpenSSL 1.0.0, which is no longer support by the OpenSSL project. You need to upgrade to a newer version of OpenSSL my python version is: Python 2.7.10 ansible: ssh version: OpenSSH_5.3p1, OpenSSL 1.0.0-fips 29 Mar 2010

How to loop over this dictionary in Ansible?

Say I have this dictionary war_files: server1: - file1.war - file2.war server2: - file1.war - file2.war - file3.war and for now I just want to loop over each item (key), and then over each item in the key (value). I did this - name: Loop over the dictionary debug: msg="Key={{ item.key }} value={{ item.value }}" with_dict: "{{ war_files }}" And I get this. It is of course correct, but is NOT what I want. ok: [localhost] => (item={'value': [u'file1.war', u'file2.war'],

Ansible Get the hostname from the hosts file

I would like to get another host from one of my templates. Given the following hosts file: [vm] vm_hostname [monitoring] monitoring_hostname How can I access monitoring_hostname from a template? I tried: monitor: {{ hostvars['monitoring'][0] }} NB: I can't just use monitor: monitoring_hostname because my hosts file is dynamically generated.

ansible playbook : changes not getting reflected

I have written ansible-playbook to configure hostname on VyOS server. Playbook is not giving any errors, But changes are not getting reflected on VyOS Here is the playbook: --- - hosts : server1 vars: inventory_hostname : vyos_host name : setting host name vyos_config lines - set system host-name {{ inventory_hostname }} default host file i am using is : /etc/ansible/project/hostfile [server1] [sever2]

Ansible - Looping through a list to specify many arguments to a single command

I'm would like to use Ansible to create a cronjob that will report disk usage statistics. This requires multiple --disk-path arguments. I need to pass in a list, iterate through, and create something along the lines of /usr/bin/disk-monitor-script --disk-path={{ item 1 }} --disk-path={{ item 2 }} # etc.. Given a variable length list along the lines of [item1, item2, etc..] It would be trivial to execute the command many times to create many cronjobs using with_items, though I would like to av

Ansible Synchronize from localhost to another host which is not the playbook host

I'm running an Ansible playbook for host_a. Some tasks I delegate to host_b. Now I would like to use the synchronize module to copy a directory from localhost to host_b. But delegate_to is the wrong option here, since this results in copying from host_b to host_a. Is there a possibility to do that? - hosts: host_a tasks: - name: rsync directory from localhost to host_b synchronize: # files on localhost src: files/directory dest: /directory/on/host_b # delegate

Ansible Is path of the inventory file accessible to playbooks?

I have a hierarchy of inventories like this: inventories foo foo1/hosts foo2/hosts bar bar1/hosts bar2/hosts Normally, I invoke ansible with explicit full path: ansible -i inventories/bar/bar1 .... However, some of the playbooks can run on the combined inventories: ansible -i inventories/bar .... This joins the multiple hosts files together, just as I want. However, I do not see a way for the tasks and templates to discern, which particular sub-inventory(ies) the hos

Allow certain roles to be run multiple times in an Ansible playbook

I made a role whose only job is to download and unpack binary packages from Artifactory. Just about everything I want to install requires me to use this role. I have a deployment with three major components, and each component will be pulled from Artifactory using this same reusable role. The role takes parameters, for example the name of the package being installed, the Artifactory URL where the binary can be downloaded from. The reusable role is called from /meta/dependancies. The problem

Ansible Conditionals: check type of element

I'm looking for a syntax to check if a variable contains any subelements or is just a string. Lets say I have a file vars/myvars.yml myvars: { key1: { greeting: "hello" }, key2: { greeting: { en: "hi", fr: "bonjour" } } } I'm looking for a condition to only accept a string and no object. So in this case, key1.greeting should match the condition, but key2.greeting should not. --- - name: test vars_files: - vars/myvars.yml hosts: all tasks: - debug:

NXOS Ansible "Connection failure: timed out"

I am very new to Ansible and am trying to run my first playbook against a nexus 5600. I am using the cisco-programmable-fabric playbook I have connectivity to the N5K, and can ping it from the Centos7 VM. I can also access the NXAPI sandbox via the browser. When I run the playbook I the errors shown in the picture. One host gets gets a connection timed out error. The host "mt-l1" has an error with a redirect. Ansible version is 2.5.1 and python version is 2.7.5. Errors NXAPI Config host

Ansible says parameter does not exist

I've got a very strange issue with Ansible. My playbook has a task which needs line: "hostssl all postgres {{ hostvars[item['ansible_default_ipv4']['address'] in a lineinfile operation. When this gets invoked without --limit=one_host, it runs perfectly, yet if I specify --limit=one_host, the playbook throws an error when it hits this task saying {"msg": "The task includes an option with an undefined variable. The error was: 'dict object' has no attribute 'ansible_default_i

Referencing Ansible Variables

I am new to Ansible and I am attempting to work on getting user access under control. I found this playbook from Galaxy: I was also reading from this source to help manage different environments: So I have the following setup: vagrant@ansible:~/ansible$ tree ├── ansible.cfg ├── debug.yml ├── dev_site.yml ├── filter_plugins ├── group_vars

How to fix "false" being evaluated to True in Ansible (Jinja2 templates)

How to make sure Jinja2 templates used within Ansible plays / roles are prone to "false" being evaluated to True? Background: Boolean handling in Ansible is tricky and may lead to an unexpected results when used along with Jinja2 templating. Turns out that Ansible handles differently "false" value: When used in when clause it evaluates to False When used in Jinja2 template it evaluates to True Take a look at this simple example: --- - name: Sample play hosts: localhost gather_facts

Ansible How to escape quotes when using the command module?

Suppose I have this SQL query: GRANT ALL PRIVILEGES ON secrets.* TO boss@'%' IDENTIFIED BY '123456'; and I wish to run that query using Ansible's command module. On a normal shell, I would do: mysql -e 'GRANT ALL PRIVILEGES ON secrets.* TO boss@''%'' IDENTIFIED BY ''123456'';' How can an equivalent be achieved using the command module? I tried this: - command: mysql -e 'GRANT ALL PRIVILEGES ON secrets.* TO boss@''%'' IDENTIFIED BY ''123456'';' But that gives an error. Note that I am a

Ansible /etc/ansible missing PIP

I have recently reimaged my laptop with Ubuntu 18.04 and after installing Ansible(2.7.5) via PIP (python2) I have realised that /etc/ansible is missing. Removing the package and reinstalling it has not changed anything. Apart from missing the /etc/ansible Ansible is working. Any idea how to force the creation of directory on the install? Or shall I just create it manually?

Ansible didnt pass down variables between files

I was trying to use Ansible to put some jinja2 templates to a directory, e.g. path/from/*.j2 to path/to/*.txt. In my ./defaults/main.yml: --- test_var: - a: 1 b: 2 - a: 10 b: 20 In my ./tasks/main.yml: --- - name: "Copy file" include: copy-files.yml with_nested: - test_var loop_control: loop_var: test_loop In my ./tasks/copy-files.yml: --- - name: "copy {{ test_loop }}" template: src: "{{ test_loop.0.a }}" dest: "{{ test_loop.0.b }}" I got the fol

Ansible How to check if an element is contained in a list?

I have two lists list1 and list2. list1 contains a variable amount of names. list2 contains three constant names. When I loop over list1, how can I write my when condition to check if item is contained in list2 ? This is what I have tried --- - hosts: localhost vars: list1: - user1 - user2 - user3 - userN list2: - user1 - user2 - user3 tasks: - name: check debug: msg: the "{{item}}" name can be used loop: "{{ l

Ansible is getting stuck on some server which is in bad ps state?

I have an ansible playbook as shown below and it works fine most of the times. But recently what I am noticing is it is getting stuck on some of the servers from the ALL group and just sits there. It doesn't even move forward to other servers in the ALL list. # This will copy files --- - hosts: ALL serial: "{{ num_serial }}" tasks: - name: copy files shell: "(ssh -o StrictHostKeyChecking=no 'ls -1 /var/lib/jenkins/workspace/copy/stuff/*' | parallel -j20 'scp -o StrictH

Ansible unable to elevate privilege to enable mode on cisco gears

I am trying to use ansible to do some automate on our cisco devices playbook - name: change config hosts: switches gather_facts: false tasks: - name: add an acl ios_config: lines: - ip access-list standard 7 permit hosts file [switches] sw1 ansible_host= group_vars\switches.yml ansible_connection: network_cli ansible_network_os: ios ansible_become: yes ansible_become_method: enable ansible_ssh_user: ***** ansible_ss

How to copy log file from multi hosts to a host directory, file named by source host ip using ansible?

I need to analyze nginx log file from multi hosts. First, i want to copy them to a host directory. For example, i want to copy nginx error log file from 6 hosts to a destination host directory. The 6 hosts ips are - The nginx error log path is /var/log/nginx/nginx_error.log. I want to copy them to /var/log/nginx_error directory in destination host Every file is named by source host ip. How can i write playbook using ansible? [serverB] [se

Ansible append directory with file content weird behavior

I try to append the contents of two key files into a directory and while doing that I get weird data. - name: read server privkey slurp: src: "{{ directories.serverkeys.dir }}server-private.key" register: filecontents - name: set server privkey set_fact: server: "{{ server|combine({'privkey': '{{ filecontents.content }}'}, recursive=True) }}" - name: debug debug: var=server This outputs: ok: [localhost] => { "server": { "ip": "", "privk

How to dynamically select json object to be used in an Ansible task?

Is it possible to select which json object to use based on some dynamic criteria? I have a yml file: - name: Get data uri: url: "foo/get_data/{{}}" return_content: yes with_items: "{{stuff_names}}" register: app_out - name: Use data uri: url: "foo/use_data/item.json[0].id" method: POST with_items: "{{ app_out.results }}" Where the call to foo/get_data/<name> returns a json array with 1 or 2 items: Sample from foo/get_data/bar1: [{"id": 1, "type"

Ansible write result command to local file with loop

I've write ansible-playbook to collect the result from many network devices. Below playbook is working fine. But if I have to collect result with lot of commands. Let say 20 commands, I've to create the many task to write the results into file in my playbook. For now, I manually create the tasks to write to logs into file. Below is example with 3 commands. - name: run multiple commands and evaluate the output hosts: <<network-host>> gather_facts: no connection: local vars:

Force stop ansible playbook

Is it possible to stop an ansible playbook? I am not talking about failed_when condition or some other ansible modules, but actually killing the process!

Ansible: when variable/fact is greater than or equal to AND less than or equal to?

As the question implies, I'm trying to evaluate a fact in an Ansible role if the value is greater than or equal to a number AND less than or equal to another number; basically a range. I can't seem to find how to do this. Here's part of my playbook snippet: - name: DEBUG Snapshots to be deleted debug: msg: The snapshot for {{ inventory_hostname.split("_")[0] }} is {{ snap_age }} day(s) old and would have been deleted. when: (old_snap is defined) and (old_snap == true) and (snap_age >

Ansible URI post with Contenty-Type application/xml

I need to call a Rest API and POST data with Content-Type:application/xml using Ansible. It seems that URI module doesn't have the facility to do so. I am not sure the reason for not allowing to POST application/xml using URI module in Ansible. currently I am using shell module and use curl to achieve this. However I prefer URI module. Does anyone know the reason or any better way?

Is there a way to convert a decimal string to a hexadecimal string in Ansible 2.9?

I have a playbook that queries a server for it's SystemID which can be converted to a model number using a vendor-provided table that maps the id to a model. The server returns a decimal value but the table uses the hexadecimal equivalent. What I want to do is converted the decimal string to a hexadecimal string that can be matched with an entry in the vendor-provided table. Example: Server returns: SystemID = 1792 Matching entry in vendor table: 0x0700 I've searched in the Ansible docu

Ansible : Split a string with multiple spaces as delimiter

I am trying to split a string multiple spaces as delimiter in Ansible. - name: Build Archive files 123. set_fact: archfilesloc: "{{ archfiles.split(\" +\")[1] }}" doesnt work - name: Build Archive files 123. set_fact: archfilesloc: "{{ archfiles.split(\"\\s+\")[1] }}"doesnt work - name: Build Archive files 123. set_fact: archfilesloc: "{{ archfiles.split(\"[\\s+]\")[1] }}" doesnt work

Ansible condition in variable type list

I would like to add certain lines in a "list" type variable. I do that condition: 'true' var_list: - template: "{{ playbook_dir }}/file1.j2", dest_dir: "{{ docker_volume_basedir }}/file1.txt" - template: "{{ playbook_dir }}/file2.j2", dest_dir: "{{ docker_volume_basedir }}/file2.txt" {% if condition == 'true' %} - template: "{{ playbook_dir }}/file3.j2", dest_dir: "{{ docker_volume_basedir }}/file3.txt" {% endif %}

Ansible template tries to calculate variables in unused branch of conditions: is this a normal behaviour?

I'm using Ansible 2.8.6 and I ran into an error with the templates when using conditions. It tries to compute some parts of the variables even when these variables are only used in "unused branches" of the templates. In my case, computing these variables does not make sense and provoke an error so I don't want Ansible to compute these variables. I expected Ansible/Jinja2 to not compute them if the condition to use them is not fulfilled. Simple example of what I'm trying to explain: pb

Ansible: Is the any chance of maintain same tag same role but diffrent host name in main yml file by putting any when condition from tasks inside role

I have tried to maintain my main yml file like below --- - hosts: "{{ windows_hostname1 }}" gather_facts: no roles: - Windows - hosts: "{{ windows_hostname2 }}" gather_facts: no roles: - Windows and my tasks are inside the windows role with same tag name is there any chance of putting when condition to this hosts variable in tasks so I can diffrentiate the execution for two windows hosts. I have two windows devices which deals differenct tasks. Thanks in advanc

Ansible How to simply access an object in a JSON with keys which are integers?

I have this example: --- - hosts: localhost gather_facts: false vars: json1: {'disk_info': {'A': {'label': 'Hard disk 1'}, 'B': {'label': 'Hard disk 2'}}} json2: {'disk_info': {'0': {'label': 'Hard disk 1'}, '1': {'label': 'Hard disk 2'}}} tasks: - debug: msg="{{json1.disk_info.A}}" - debug: msg="{{item.value.label}}" loop: "{{ lookup('dict', json2.disk_info) }}" when: "'0' in item.key" Is it possible to access

ansible - block conditionnal is ignored

i have a problem xith a block in an ansible role Extract of roles/apps_nifi/tasks/main.yml : - debug: msg: "nifi_extra_instances_name is defined" when: nifi_extra_instances_name is defined - debug: msg: "nifi_extra_instances_name is not defined" when: nifi_extra_instances_name is not defined - name: Import variables for extra instances of Nifi block: - set_fact: nifi_extra_instances_vars: "{{ item.value }}" when: nifi_extra_instan

ansible playbook access first loop variable in second loop

I have list of applications paths in a file APP_DIR, need to loop through the paths and run start command. - name: start command: "{{item[1]}}" with_nested: - "{{ lookup('file', 'APP_DIR').splitlines() }}" - [ "chdir={{item[0]}} ./start", "ps -aef | grep httpd | grep -v grep"] ERROR: FAILED! => {"msg": "'item' is undefined"}. Thanks in Advance for help.

Specifying multiple default groups as hosts in an Ansible playbook

I'm looking for a way to specify multiple default groups as hosts in an Ansible playbook. I've been using this method: - name: Do things on hosts hosts: "{{ specific_hosts | default('development') }}" tasks: # do things on hosts However I'm trying to avoid specifying hosts manually (it is error-prone), and the default hosts are inadequate if I want to run the same tasks against multiple groups of servers (for instance, development and QA). I don't know if this is possible in a

use ansible facts while executing task in ansible

I am executing below ansible task based on facts value gathered via ansible. - hosts : mirth1 vars : env : dev gather_facts : true tasks: #- name: Build corresponding JSON files - name: Build a Stream shell: uptime when: tags['ha'] == 'active' Facts value gathered via ansible: "hostvars[inventory_hostname]": "{'httpd_port': 80, 'ntpserver': '', 'ans

How to get all indices of output array in Ansible

I'm gathering info on SSL certs on servers (looking for expiration date) using the find module. - name: Find certs on server find: path: /etc/ssl/custom/certs file_type: file patterns: "*.crt" recurse: yes register: find_result - debug: var: find_result The results are: ok: [server00] => { "find_result": { "changed": false, "examined": 5, "failed": false, "files": [

Ansible How can I write "echo" command in playbook (yaml)

I want to know how I can write the equivalent of the following command in an ansible playbook. echo \ "deb [arch=arm64 signed-by=/usr/share/keyrings/docker-archive-keyring.gpg] \ $(lsb_release -cs) stable" | sudo tee /etc/apt/sources.list.d/docker.list > /dev/null

  1    2   3   4   5   6  ... 下一页 最后一页 共 34 页