Ansible notes

dumping some notes on ansible for future reference

Modules

Modules are small units of work in Ansible.

Example: ansible -m ping localhost

File Module

The file module is used for manipulating files.

Create a file: ansible -m file -a "dest=hello state=touch" localhost

State in Ansible

Ansible is concerned with the state of the system.

Achieve the desired state: CHANGED or SUCCESS

Check Mode

Check mode helps analyze potential outcomes without making changes.

Example: ansible -m copy -a "dest='hello' content='world'" localhost"

Outcomes:

Use --check to reveal the state without performing the operation.

Diff Flag

Use the --diff flag to show the difference between the current state and the new state.

Handling Remote Nodes

Ansible manages remote nodes via a control node.

Define nodes in an inventory:

Command line: ansible -i 'node1, node2' -m ping node2

Inventory file:

          node1
          node[2:n]
        

Configuration options:

Command line: ansible -i inventory_file -m command -a 'cowsay "hello"' all

ansible.cfg:

          [defaults]
          inventory=inventory_file
        

Environment variable

Command Module

Execute arbitrary commands.

Example: ansible -m command -a 'cowsay "hello"' localhost

Configuration Options

Show current config: ansible-config dump

Display inventory details: ansible-inventory --list [--yaml]

SSH Connection

Ansible uses SSH by default to connect to remote nodes.

Modules are copied from the control node to the managed node and then executed.

Privilege Elevation

Use --become to elevate privileges.

Playbook

Playbooks are Ansible's configuration, deployment, and orchestration language.

Example playbook (playbook.yml):

      - name: copy module test
        hosts: localhost
        tasks:
          - copy:
              dest: hello
              content: world
          - command: cowsay "hello"
            when: ansible_distribution == "MacOSX"
    

Conditionals

Use conditionals in tasks.

    
    ansible -m setup localhost -a "filter=ansible_distribution"
    - name: my task
      var: ansible_distribution
      when: ansible_distribution == "MacOSX"
    
  

Running Playbooks

    
    - name: Example Playbook
      hosts: localhost
      tasks:
        - name: Task 1
          debug:
            msg: "Running Task 1"

        - name: Task 2
          debug:
            msg: "Running Task 2"

        - name: Task 3
          debug:
            msg: "Running Task 3"
    
  

Execute playbook: ansible-playbook playbook.yml [-v]

Use -v for more verbose output.

Tags

Use --tags to execute specific tasks within a playbook.

ansible-playbook playbook.yml --tags task1