HiveBrain v1.2.0
Get Started
← Back to all entries
snippetMinor

How to run multiple commands with command module in Ansible

Submitted by: @import:stackexchange-devops··
0
Viewed 0 times
commandswithmodulemultiplehowcommandansiblerun

Problem

I want to run couple of commands in ansible playbook I am trying below:

- name: Running multiple cmds
   command:
    - |
      cmd2
      cmd2
      cmd3
      cmd4


But i am getting an error on this task while running above code.

Update: I am trying to use below commands using command module but getting an error:

- name: install pexpect using pip
  shell: /bin/bash -c "pip install pexpect"

- name: Join system to AD 
  expect:
    command: "{{ item }}"
    loop:
      - source /etc/os-release
      - realm join --membership-software=adcli --user=username@EXAMPLE.COM --computer-ou="OU={{ env }},OU={{ account }},OU=XXXX,OU=XXXXXX,DC=XXXXXXX,DC=XXXXXXX" --os-name="$PRETTY_NAME" --os-version="$VERSION" 
    responses:
        Password for *: "{{ username | b64decode }}"


Error:

TASK [adjoin : Join system to AD] ***********************************************************************************************************************************************************
fatal: [localhost]: FAILED! => {"msg": "The task includes an option with an undefined variable. The error was: 'item' is undefined\n\nThe error appears to be in '/tmp/ansiblepull/playbooks/roles/adjoin/tasks/main.yml': line 58, column 3, but may\nbe elsewhere in the file depending on the exact syntax problem.\n\nThe offending line appears to be:\n\n\n- name: Join system to AD\n  ^ here\n"}


Can anyone help me in solving this.

I am getting an error while syntax-check as well.

Solution

The Ansible documentation states that the command module doesn't get a shell


The command(s) will not be processed through the shell

The command module takes the command as an argument, so you can't have list as you've written there. You could do the same thing in a loop: with command: {{ item }} :

- name: "Run {{ item }}"
  command: "{{ item }}"
  loop:
    - cmd2
    - cmd2 
    - cmd3


You could also have several command: tasks instead.

However, this is generally considered bad practice (E.g. E303 from Ansible Lint rules) because it tends to break idempotency. It would be better to decompose those commands into something that uses Ansible modules.

Code Snippets

- name: "Run {{ item }}"
  command: "{{ item }}"
  loop:
    - cmd2
    - cmd2 
    - cmd3

Context

StackExchange DevOps Q#11214, answer score: 4

Revisions (0)

No revisions yet.