Ansible - Shell

Card Puncher Data Processing

About

This article shows how to execute a command via a shell with ansible and the ansible shell module 1)

Example

Basic

- name: Move file
  become: yes
  become_user: "{{ prometheus_user_name }}"
  shell:
    cmd: "/bin/cp {{ prometheus_install_dir }}/{{ prometheus_node_exporter_name }}/* {{ prometheus_home }}"
    chdir: somedir/
  args:
    executable: /bin/bash

Capture the output as variable

- name: Determine the Cgroup version
  shell:
    cmd: |
      stat -fc %T /sys/fs/cgroup/
  register: cgroupFs 

use the stdout conditionaly

- name: CgroupV2 - Set the CPU 50 group conf {{ cgroup_cpu_50 }}
  when: cgroupFs.stdout == 'cgroup2fs'
  shell:
    cmd: |
      cgset -r cpu.weight=50 {{ cgroup_cpu_50 }}

Doing a conditional action if the command fails

- name: Get helm installed version
  ansible.builtin.shell: helm version | grep -oP 'Version:"v\K[0-9.]+'
  register: helm_version_output
  changed_when: false
  ignore_errors: yes


- name: Set helm installed version
  when: helm_version_output.rc == 0
  set_fact:
    installed_helm_version: '{{ helm_version_output.stdout }}'

- name: Set helm installed version
  when: helm_version_output.rc != 0
  set_fact:
    installed_helm_version: '0'





Discover More
Card Puncher Data Processing
Ansible - Command

command is the default module of the ansible command line and helps you execute adhoc (on the fly) command. shell module
Card Puncher Data Processing
Playbook Variable

This article is variable inside a playbook, task, ... Single value Boolean Block of text Order...



Share this page:
Follow us:
Task Runner