Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use the response from shell inside yml for Ansible playbook

Tags:

yaml

ansible

I want to install MongoDB via Ansible playbook, I am following the instruction in: https://www.howtoforge.com/tutorial/install-mongodb-on-ubuntu-16.04/

For the step about "Step 2 - Create source list file MongoDB"

I should use:

echo "deb http://repo.mongodb.org/apt/ubuntu "$(lsb_release -sc)"/mongodb-org/3.2 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-3.2.list

while it get the ubuntu version with the following command:

$(lsb_release -sc)

How can I do it via yml file and run it via ansible palybook? I used the below yml command but it is not working and gives me error since I use shell command "$(lsb_release -sc)" inside my script

- name: Create source list file MongoDB
  sudo: yes
  lineinfile: >
    line="deb http://repo.mongodb.org/apt/ubuntu "$(lsb_release -sc)"/mongodb-org/3.2 multiverse"
    dest=/etc/apt/sources.list.d/mongodb-org-3.2.list
    state=present
    create=yes
like image 708
Papal Avatar asked Oct 24 '17 15:10

Papal


People also ask

How do you capture command output in Ansible?

To capture the output, you need to specify your own variable into which the output will be saved. To achieve this, we use the 'register' parameter to record the output to a variable. Then use the 'debug' module to display the variable's content to standard out.

How do I register Ansible shell output?

In Ansible, you can run any shell command on your Ansible hosts, the hosts you will be configuring with Ansible. These shell commands may have outputs. By default, the output is ignored. If you want to store the output in a variable and use it later, then you can use the Ansible register module.

How do you pass arguments in Ansible playbook?

To pass a value to nodes, use the --extra-vars or -e option while running the Ansible playbook, as seen below. This ensures you avoid accidental running of the playbook against hardcoded hosts.


2 Answers

There is apt_repository module in Ansible:

- apt_repository:
    repo: deb http://repo.mongodb.org/apt/ubuntu {{ ansible_distribution_release | lower }}/mongodb-org/3.2 multiverse
    state: present
like image 101
Konstantin Suvorov Avatar answered Sep 27 '22 18:09

Konstantin Suvorov


You can register the result of one task, including its stdout, as a variable then use it in later tasks:

- name: Work out the distribution
  command: lsb_release -sc
  register: result

- name: Create source list file MongoDB
  sudo: yes
  lineinfile: >
    line="deb http://repo.mongodb.org/apt/ubuntu {{ result.stdout }}/mongodb-org/3.2 multiverse"
    dest=/etc/apt/sources.list.d/mongodb-org-3.2.list
    state=present
    create=yes
like image 23
Bracken Avatar answered Sep 27 '22 17:09

Bracken