hazzy
hazzy

Reputation: 107

wild card in command module in Ansible

I have a directory /tmp/abc. In /tmp/abc i have 5 files few are text files one property file and one jar file. I want to run that jar file.

But the issue is that the jar name is dynamic based on build. Is there any way that i can run the jar without hard coding and without passing it as extra variable(because i wont be knowing the name)?

Right now what i am trying to do is to list the content of file and then try to save that in a var and then trying to use wild card to run the jar. But it is not working

Here is my ansible code:

- name: read content of directory
  command: "ls /tmp/abc"
  register: file_content

- name: run the jar
  command: "java -jar /tmp/abc/*.jar"

Is there any better way of doing it?

Thanks in advance for help.

Upvotes: 1

Views: 559

Answers (1)

Zeitounator
Zeitounator

Reputation: 44808

Is there any better way of doing it?

Yes. Use the find module to search for the exact file name of your jar and run it from its absolute path.

Find returns a list of matches in the files list. If you know and trust your file structure, you just have to keep the first and only result and get its path attribute.

Here is an example.

My test directory created from your description

/tmp/abc/
├── a.txt
├── b.txt
├── c.properties
├── d.jar
└── e.txt

My playbook

---
- name: Run dynamically named jar
  hosts: localhost
  gather_facts: false

  tasks:

    - name: find jar files in /tmp/abc
      find:
        paths:
          - /tmp/abc
        patterns:
          - "*.jar"
        file_type: file
        recurse: no
      register: jarsearch

    - name: Show the command we would run
      debug:
        msg: "java -jar {{ (jarsearch.files | first).path }}"

And the result

$ ansible-playbook test.yml 

PLAY [Run dynamically named jar] **********************************************************************************************************************************************************************************

TASK [find jar files in /tmp/abc] *********************************************************************************************************************************************************************************
ok: [localhost]

TASK [Show the command we would run] ******************************************************************************************************************************************************************************
ok: [localhost] => {
    "msg": "java -jar /tmp/abc/d.jar"
}

PLAY RECAP ********************************************************************************************************************************************************************************************************
localhost                  : ok=2    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0 

Upvotes: 2

Related Questions