3

I'm trying to create an EBS role for my Ansible scripts. I'm going to be creating the EBS volume and attaching it myself for now through the console. I want this role to run commands and mount the drive if the drive isn't already mounted, but skip this if it's already mounted.

I have host specific vars that give a list of disks and mount points:

ebs_vols:
  - drive: /dev/sdb
    mount_point: /mnt/ebs1
    directory: /var/lib/mysql
  - drive: /dev/sdc
    mount_point: /mnt/ebs2
    directory: /var/backups

I want to have my task check each drive with a df command and see if it's mounted. Then skip commands if the drive is mounted:

- name: Check if drives are already mounted
  shell: df | grep "{{item.drive}}" | wc -l
  with_items: "{{ebs_vols}}"
  register: ebs_checked

- name: output debug
  debug: var=ebs_checked

- name: Make filesystem
  filesystem:
    fstype: xfs
    dev: "{{item.item.drive}}"
  when: "{{item.stdout}} == 0"
  with_items: ebs_checked.results

When I run it, it seems to check each disk just fine because the output of the debug is an object with the correct drives and stdout. The problem is with the Make filesystem task. The errors out with the following error:

The conditional check '{{item.stdout}} == 0' failed. The error was: error while evaluating conditional ({{item.stdout}} == 0): 'ansible.vars.unsafe_proxy.AnsibleUnsafeText object' has no attribute 'stdout'\n\n

What am I missing here and what is the best way to skip commands if the drive is already mounted?

techraf
  • 64,883
  • 27
  • 193
  • 198
gkrizek
  • 978
  • 3
  • 10
  • 18

2 Answers2

6

You can't use "bare variables" anymore in Ansible. The following line causes Ansible to interpret the ebs_checked.results value as a string:

with_items: ebs_checked.results

Use the correct syntax instead:

with_items: "{{ ebs_checked.results }}"
techraf
  • 64,883
  • 27
  • 193
  • 198
  • Ah, I see. Rookie mistake. I'm new to Ansible and I guess I was expecting some kind of Syntax error instead of it trying actually execute it. Thanks! – gkrizek Feb 20 '17 at 22:49
  • There is no syntax error. `item` is assigned a string value of `ebs_checked.results` and you got an error that it doesn't contain the `stdout` key you tried to use. – techraf Feb 21 '17 at 00:10
  • This use of bare variables in `with_` loops was deprecated in Ansible 2.0, and removed in 2.2 - see the [Ansible 2.0 porting guide](https://docs.ansible.com/ansible/porting_guide_2.0.html#deprecated). – RichVel Mar 05 '17 at 10:35
2

You may want to try:

- name: Check if drives are already mounted
  command: '/bin/mountpoint -q {{item.directory}}'
  with_items: '{{ebs_vols}}'
  register: ebs_checked
  changed_when: "ebs_checked.rc != 0"

Also, ansible's setup module does populate an ansible_mounts array, but I haven't had a chance to see if it would be helpful in this context.

Sean Summers
  • 2,514
  • 19
  • 26