ansible,ansible-playbook , How to run a task when variable is undefined in ansible?


How to run a task when variable is undefined in ansible?

Question:

Tag: ansible,ansible-playbook

I am looking for a way to perform a task when ansible variable is not registers /undefined e.g

-- name: some task
   command:  sed -n '5p' "{{app.dirs.includes}}/BUILD.info" | awk '{print  $2}'
   when: (! deployed_revision) AND ( !deployed_revision.stdout )
   register: deployed_revision

Answer:

From the ansible docs: If a required variable has not been set, you can skip or fail using Jinja2’s defined test. For example:

tasks:

- shell: echo "I've got '{{ foo }}' and am not afraid to use it!"
  when: foo is defined

- fail: msg="Bailing out. this play requires 'bar'"
  when: bar is not defined

So in your case, when: deployed_revision is not defined should work


Related:


How to conditionally check the state of an openstack instance


cloud,state,conditional-statements,ansible,openstack
I am trying to conditionally check the state of an openstack cloud instance in my playbook. The playbook itself takes the name of a cloud instance as a parameter and then deletes it by setting the state to absent using nova compute. What I want to do is check if...

Triggering Jenkins to run application tests when GitHub PR is created


git,jenkins,continuous-integration,ansible,continuous-deployment
I am a noob to Jenkins, and I have a Jenkins server that runs an ansible playbook to deploy the app. I would like to be able to have Jenkins run an ansible playbook which runs application python tests when a GitHub pull request is opened. I would then like...

Only check whether a line present in a file (ansible)


ansible,ansible-playbook
I need to check whether a particular line present in a file or not in ansible. Basically I need to convert following command to ansible task. My goal is to only check. grep -Fxq "127.0.0.1" /tmp/my.conf ...

How to import Python modules for user in Jinja2 template


datetime,jinja2,ansible,ansible-playbook
I want to create a file name by formatting datetime.now(). It is simple enough in Python, but the datetime module needs to be imported. How can I import it for use in a Jinja2 template? For example, in this Ansible task: - name: myTask shell: echo "123" > /tmp/{{datetime.now().strftime("%Y-%m-%d_%H-%M-%S")}}.zaz ...

Ansible git module not checking out a branch


git,ansible
I'm using ansible to checkout my webapplication on EC2 web instances. My code is as followed: - name: Checkout the source code git: accept_hostkey=yes depth=5 dest={{ webapp_dir }} force=yes key_file=/var/tmp/webapp_deploy_key [email protected]:MyRepo/web-app.git update=yes version={{ webapp_version }} register: git_output As long as webapp_version = masterit works perfectly. But as soon as I...

How to use Erlang configuration files with Python J2 template?


python,jinja2,ansible
I would like to deploy with Ansible some configuration files the following way: - name: Deploying test configuration template: src={{ item }}.j2 dest={{ basho_bench_home_dir }}/conf/{{ item }} sudo: yes with_items: - http_fix_1min.conf.template - http_max_1min.conf The files have lines like these: {mode, max}. {duration, 1}. {concurrent, 32}. This ultimately breaks the...

How to pass variable that's a dictionary into Ansible Role?


yaml,ansible,ansible-playbook
I want to pass some values into an Ansible role, but I can't find any examples in the docs that show how to pass in a variable that's a dictionary. Here is what I'd like to pass in, but my YAML syntax is off: roles: - { role: postgresql, postgresql_users:...

Retrying ansible playbook with Vagrant


vagrant,ansible,ansible-playbook,vagrantfile
Is there any way to retry playbooks playbooks from where they failed? I'm starting it with vagrant provision Thanks...

Ansible-pull with no inventory limitations


ansible,ansible-playbook
I want to have a set of git repos with base application config playbooks in them such that all I need to do with any VM, regardless of its name or role or how long its been around, to get the base config installed is to run an ansible-pull command...

Optimizing Ansible Transport\SSH for Unconventional Networks


networking,optimization,ssh,ansible
I'm wondering how to optimise Ansible to work with a network radically different to one where use cases where Accelerate and default might not necessarily be beneficial. In this scenario I'm not dealing with a virtual network, nor am I dealing with servers. I'm dealing with hundreds of embedded, with...

Create and access dict in Ansible playbook


ansible,ansible-playbook
I'm trying to set a variable in an Ansible playbook based on an existing variable's value which could be one of many different strings. It's basically a case/switch statement and this is the logic (with incorrect syntax): if {{ existing_ansible_var }} == "string1" new_ansible_var = "a" else if {{ existing_ansible_var...

Ansible set_fact across plays


ansible,ansible-playbook
I have to run an ansible playbook to execute the following tasks 1) Calculate date in YYYY_MM_DD format and then use this prefix to download some file from aws to my local machine. The filename is of the following format 2015_06_04_latest_file.csv 2) I have to then create a folder by...

Ansible random UUID generation


ansible
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 the following error: fatal: [localhost] =>...

Case statement for setting var in Ansible/Jinja2


jinja2,ansible,ansible-playbook
I'm using Ansible with Jinja2 templates, and this is a scenario that I can't find a solution for in Ansible's documentation or googling around for Jinja2 examples. Here's the logic that I want to achieve in Ansible: if {{ existing_ansible_var }} == "string1" new_ansible_var = "a" else if {{ existing_ansible_var...

Ansible command to check the java version in different servers


unix,ansible,ansible-playbook
I am writing a Test case using ansible.There are totally 9 servers in which I need to check whether the installed java version is 1.7.0 or not? If it is less than 1.7.0 then test case should fail. Can anyone help me to write this Test case as I am...

Is the server running locally and accepting connections on Unix domain socket “/var/run/postgresql/.s.PGSQL.5432”


postgresql,ansible
I am provisioning a 'Precise64' Ubuntu machine via Ansible, I am encountering an error when ensuring that the database is in fact created. I am using most of https://github.com/jcalazan/ansible-django-stack - name: Install PostgreSQL apt: name={{ item }} update_cache={{ update_apt_cache }} state=installed with_items: - postgresql - postgresql-contrib - python-psycopg2 tags: packages...

Combine two default Ansible host files including one being ec2.py?


ansible,ansible-playbook
I'm using Ansible is a mixed environment of AWS and non-AWS machines. I'd like to avoid passing hosts on the command line. How do I combine multiple host files in Ansible and make it the default? The current recommendation on the Ansible site is to override /etc/ansible/hosts with ec2.py. which...

Ansible inventory parameters for pem key


osx,ansible
I'm just getting started with Ansible but I'm running into various issues. The latest is my ssh keys aren't being picked up by the 'hosts' inventory file. The file's contents are: [my host] my-dev ansible_ssh_host=54.79.31.51 ansible_ssh_private_key_file=/Users/dev/.ssh/dev.pem ansible_ssh_user=ec2-user And the error I get when executing ansible all -m ping -vvvv <54.79.31.51>...

can roles and tasks exist in the same playbook?


ansible,ansible-playbook
--- # 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 }}" } - { role: vim, sudo_user: "{{ user }}" } For some reason the create...

Manage whole crontab files in Ansible


cron,ansible
I have a crontab containing around 80 entries on a server. And I would like to manage that crontab using Ansible. Ideally I would copy the server's crontab to my Ansible directory and create an Ansible task to ensure that crontab is set on the server. But the cron module...

Ansible git clone as root


ansible
I'm using the following role for Ansible in order to clone a project in my vagrant setup: - name: Clone Repository git: repo: https://login:[email protected]/team/repo.git dest: /home/vagrant/workspace/ accept_hostkey: true The cloning is working as expected, but the main issue is that the directory workspace and all it's content is now owned...

Running bash commands in Ansible task


python,mysql,ansible,ansible-playbook
I am porting a Makefile into a series of Ansible tasks. The make file has these two lines of code which are troubling me when it comes to ansible: SERVERS := shell mysql "select hostname from servers" EASY_INSTALL := wget https://bootstrap.pypa.io/ez_setup.py -O - | python Firstly, what's the appropriate Ansible...

How to traverse a nested dict structure with Ansible?


yaml,ansible,ansible-playbook
I have the following dict structure variable in an ansible playbook: apache_vhosts: - name: foo server_name: foo.com server_aliases: - a.foo.com - b.foo.com - c.foo.com - name: bar server_name: bar.com server_aliases: - d.bar.com - e.bar.com - f.bar.com I need to create a symlink for each of the server_name and server_aliases domains,...

Passing values dynamically to an Ansible inventory - Python


python,ansible
I'm trying to Ansible's Python API in order to write a test API (in Python) which can take advantage of a playbook programmatically and add new nodes to a Hadoop cluster. As we know, at least node in the cluster has to be the Namenode and JobTracker (MRv1). For simplicity...

How to add a disk to a Google Compute Engine instance with the gce_pd Ansible module?


google-compute-engine,ansible,ansible-playbook
I'm new to Ansible, but I have a working playbook that creates Google Compute Engine instances. I followed the Ansible section of Compute Engine Management with Puppet, Chef, Salt, and Ansible - Appendix to achieve this. Now I would like to extend the playbook to add extra persistent disks to...

Openstack Heat & Ansible. VM spinup and App deployment


ansible,openstack
I am spinning up new VM's using openstack heat template and get the IP list of the newly spun up VM's. I am using Ansible scripts for the same. I am able to get the new list of IP's from the heat and I am able to deploy an app...

Can I set remote_user in host_vars or group_vars?


ansible,ansible-playbook
I'm starting to write my first serious playbook in ansible. Something I'd like to do is to specify different remote_user values per host. I'm able to set remote_user in ansible.cfg, through the CLI -u option and even in play variables, like so: --- - name: install dependencies hosts: all sudo:...

One loop over multiple Ansible tasks


loops,ansible,ansible-playbook
I've created an Ansible playbook that creates a cloud instance and then installs some programs on the instance. I want to run this playbook multiple times (without using a bash script). Is it possible to use a loop to loop over those two tasks together (I.E. One loop for two...

How to set a variable using dynamic inventory using Ansible


amazon-web-services,amazon-ec2,ansible,ansible-playbook,rds
I am looking for method to set a variable in ansible playbook using inventory information received from dynamic inventory. For example if we have a sample playbook like --- - hosts: localhost connection: local tasks: - set_fact: rds_hostname="{{ rds_mysql }}" #set rds endpoint from ec2.py - debug: var=rds_hostname I am...

how to read each element of an yaml map


yaml,ansible
I am trying to access all the elements of a yaml object, any suggestions would be helpful: object: element1: "value1" element2: "value2" element3: "value3" The above object is defined in group_vars/all file so that it can be accessed by other tasks. - name: pass values to script debug: "msg={{ item...

`with_dict expects a dict` - Ansible global composer and kosssi.composer


php,composer-php,ansible,kosssi-composer
I'm trying to use the kosssi.composer Ansible role to install a global composer instance as well as a couple of composer packages. --- - hosts: myhosts remote_user: vagrant sudo: true roles: - { role: kosssi.composer, composer_path_env: true, composer_home_path: /opt/composer, composer_home_owner: vagrant, composer_home_group: vagrant, composer_global_packages: phpunit/phpunit: '@stable' phing/phing: '@stable' } I've...

Vagrant with ansible stop when meet console questions


mongodb,vagrant,ansible
I'm installing mongo extension for PHP in my vagrant with this task --- - name: Intall MongoDb PHP extension sudo: yes command: "pecl install mongo" - name: Copy mongo extension INI to mods-available folder template: > src=mongodb_extension.ini.j2 dest={{ php_conf_dir }}/mongodb.ini owner=root group root mode=644 - name: Enabling mongo config in...

ansible playbook execute in this order: task, role, task, role, task


ansible
Forgive my newbie question, but I would like to execute three tasks and use two roles in a playbook, in the order: task role task role task This is what I have so far (task, role, task): --- - name: Task Role Task hosts: 127.0.0.1 connection: local gather_facts: false pre_tasks:...