Skip to main content

Executing Commands

1. Using Command Module

Parameter Description Default Notes
cmd Command to execute required Must be a valid shell command
chdir Change to this directory before executing the command null Can be used to set working directory
creates Run command only if this file does not exist null Useful for idempotent operations
removes Run command only if this file exists null Useful for cleanup tasks
warn Enable or disable warning messages true Set to false to suppress warnings

Example: Basic command execution

- name: Run a command
  command: ls -l

Example: Command with environment variables

- name: Run command with environment
  command: echo $HOME
  environment:
    HOME: /home/user
Note: The command module does not support shell features like pipes or redirections. Use the shell module for such cases.

2. Using Shell Module

Parameter Description Example
cmd Command to execute ls -l
chdir Change to this directory before executing the command /tmp
creates Run the command only if this file does not exist /tmp/myfile.txt
removes Run the command only if this file exists /tmp/oldfile.txt
warn Set to false to suppress warnings false

Example: Running a shell command

- name: List files in directory
  shell: ls -l
  args:
    chdir: /home/user

Example: Conditional execution

- name: Create file only if it doesn't exist
  shell: touch /tmp/newfile.txt
  args:
    creates: /tmp/newfile.txt

3. Using Raw Module

Parameter Description Example
cmd Command to execute on the remote host ls -l /tmp
creates Only run the command if this file does not exist /tmp/lockfile
removes Only run the command if this file exists /tmp/oldfile
chdir Change to this directory before executing the command /home/user
warn Whether to warn if the command is not found false

Example: Running a raw command

- name: List files in /tmp
  raw:
    cmd: ls -l /tmp

Example: Conditional execution

- name: Create lockfile only if it doesn't exist
  raw:
    cmd: touch /tmp/lockfile
    creates: /tmp/lockfile

4. Setting Working Directory

Parameter Description Default
chdir Change into this directory before running the command None

Example: Setting Working Directory

- name: Run command in specific directory
  command: ls -la
  args:
    chdir: /home/user/project

5. Creating Files Before Command

Option Values Notes
dest path/to/file Destination path where the file will be created
content string Content to write into the file
mode 0644 File permissions (octal format)
owner user User owner of the file
group group Group owner of the file

Example: Creating a file with content

- name: Create a file with content
  ansible.builtin.copy:
    dest: /etc/myapp/config.ini
    content: |
      [settings]
      debug = true
      port = 8080
    mode: '0644'
    owner: root
    group: root
Note: The copy module is used here to create and populate the file. If the file already exists, it will be overwritten.

6. Removing Files After Command

Option Values Notes
file path/to/file Path to the file to be removed
state absent Ensures the file or directory is absent
force true | false If true, removes read-only files and directories

Example: Remove a file after command execution

- name: Remove temporary file after command
  ansible.builtin.file:
    path: /tmp/temp_output.txt
    state: absent
Note: The file module can also remove directories recursively if state: absent and recurse: true are specified.

7. Running Scripts

Parameter Description Example
script Path to the script file to execute script: /path/to/script.sh
args Arguments to pass to the script args: "--verbose --output=json"
chdir Change to this directory before running the script chdir: /home/user/project
creates Run only if this file does not exist creates: /tmp/script_output.txt
removes Run only if this file exists removes: /tmp/script_output.txt

Example: Running a Bash Script

- name: Run a bash script
  script: /opt/scripts/deploy.sh
  args: "--env=prod --version=1.0"
  chdir: /opt/scripts

Example: Conditional Script Execution

- name: Run cleanup script only if output exists
  script: /opt/scripts/cleanup.sh
  removes: /tmp/deployment_output.txt
Note: The script module executes scripts on the target host, not the Ansible control node. Ensure that the script has proper permissions and is executable.

8. Changing Command Status

Option Values Description
changed true / false Indicates whether the command resulted in a change to the system state
failed true / false Indicates whether the command execution failed
rc 0 / 1 / 2 etc. Return code from the executed command; 0 typically means success

Example: Using changed status in a task

- name: Check if a file exists and report status
  command: test -f /etc/ansible/file.txt
  register: result
  changed_when: result.rc == 0

- name: Output whether the command changed anything
  debug:
    msg: "Command changed system state: {{ result.changed }}"

9. Capturing Output

Parameter Description Example
register Stores the result of a task in a variable for later use
- name: Capture output of command
  command: echo "Hello World"
  register: cmd_output
delegate_to Runs the task on a different host than the one specified in hosts
- name: Run command on different host
  command: whoami
  delegate_to: "{{ groups['webservers'][0] }}"
  register: user_result

Example: Using Registered Variables

- name: Store command output
  command: ls -l /tmp
  register: list_output

- name: Display captured output
  debug:
    msg: "Files in /tmp: {{ list_output.stdout_lines }}"

- name: Use captured output in a condition
  command: echo "{{ item }}"
  loop: "{{ list_output.stdout_lines }}"
  when: "'config' in item"

Example: Capturing Output from a Script

- name: Run a script and capture its output
  command: /path/to/script.sh
  register: script_result

- name: Log the output
  debug:
    msg: "Script result: {{ script_result.stdout }}"

- name: Fail if script returns error
  fail:
    msg: "Script failed with exit code {{ script_result.rc }}"
  when: script_result.rc != 0

10. Setting Environment Variables

Variable Value Description
ansible_env {} Dictionary of environment variables to set for the task
environment {} Alias for ansible_env, used in some modules

Example: Setting environment variables in a task

- name: Run command with custom environment
  command: echo $MY_VAR
  environment:
    MY_VAR: "custom_value"
    PATH: "/usr/local/bin:/usr/bin:/bin"
Note: Environment variables set via environment or ansible_env are applied to the command execution context and do not persist beyond the task.

11. Running as Different User

Option Values Description
become true Enable privilege escalation to run as a different user
become_user root User to switch to when running the task
become_method sudo Privilege escalation method (e.g., sudo, su)
become_flags -H Flags to pass to the privilege escalation method (e.g., -H for home directory)

Example: Running a Task as Root

- name: "Run command as root"
  command: "ls -l /root"
  become: true
  become_user: root

Example: Using Different Privilege Escalation Method

- name: "Run command with su"
  command: "whoami"
  become: true
  become_user: "admin"
  become_method: "su"

12. Understanding Command vs Shell

Aspect Command Module Shell Module
Module Name command shell
Execution Context Direct execution without shell interpretation Executes through a shell (e.g., /bin/sh)
Supports Pipes & Redirection No Yes
Supports Variable Expansion No Yes
Security More secure; less vulnerable to shell injection Less secure; susceptible to shell injection if input is not sanitized
Performance Faster due to direct execution Slower due to shell overhead

Example: Using the command module

- name: Execute a command directly
  command: ls -l /home

Example: Using the shell module

- name: Execute a command with shell features
  shell: echo $HOME > /tmp/home_dir.txt
Note: The command module is preferred for security and performance when shell features are not required.
Warning: The shell module should be used cautiously with user-provided input to avoid shell injection vulnerabilities.

Was this article helpful?