UsefulCommands - Alex-Burgess/ansible-demo GitHub Wiki

Build whole Environment

$ ansible-playbook -i inventories/testing/hosts main.yml

Via sudo

$ sudo -u ansible /home/ansible/.local/bin/ansible-playbook -i inventories/testing/hosts main.yml

Test ping on servers of specified type

$ ansible webservers -m ping

Run command on servers of specified type

$ ansible webservers -m command -a "hostname"

Run shell commands on servers of specified type

$ ansible webservers -a "hostname"

Run command with become

$ ansible webservers -a "id" --become --become-user=root

Dynamic inventory

Basic ping:

$ ansible -i ec2.py -e 'ansible_ssh_user=apache' -m ping tag_Type_Webserver

To run a command against multiple tags:

$ ansible -i ec2.py -e 'ansible_ssh_user=apache' -m ping "tag_Environment_test:&tag_Type_Webserver"

Or, a second option:

$ ansible -i ec2.py --limit "tag_Environment_test:&tag_Type_Webserver" -e 'ansible_ssh_user=apache' -m ping all

Get Ansible Controller IPs

$ aws ec2 describe-instances --query 'Reservations[*].Instances[*].{PrivateIpAddress:PrivateIpAddress,  PublicIpAddress:PublicIpAddress, State:State.Name}' --filters 'Name=instance-state-name,Values=running' 'Name=tag:Type,Values=AnsibleController' 'Name=tag:Environment,Values=test' 'Name=tag:Application,Values=AnsibleDemo'

Or for more detail:

$ aws ec2 describe-instances --query 'Reservations[*].Instances[*].{PrivateIpAddress:PrivateIpAddress,  PublicIpAddress:PublicIpAddress, State:State.Name}' --filters 'Name=instance-state-name,Values=running' 'Name=tag:Type,Values=AnsibleController' 'Name=tag:Environment,Values=test' 'Name=tag:Application,Values=AnsibleDemo'

Get Webserver IPs

aws ec2 describe-instances --query 'Reservations[*].Instances[*].{IP:PrivateIpAddress,AZ:Placement.AvailabilityZone}' --output text --filters 'Name=instance-state-name,Values=running' 'Name=tag:Type,Values=Webserver' 'Name=tag:Environment,Values=test' 'Name=tag:WebApp,Values=ansiblewebdemo'

Or for more detail:

$ aws ec2 describe-instances --query 'Reservations[*].Instances[*].{PrivateIpAddress:PrivateIpAddress,  PublicIpAddress:PublicIpAddress, State:State.Name}' --filters 'Name=instance-state-name,Values=running' 'Name=tag:Type,Values=Webserver' 'Name=tag:Environment,Values=test' 'Name=tag:WebApp,Values=ansiblewebdemo'

Start ssh-agent and add ssh key

$ ssh-agent bash
$ ssh-add ~/.ssh/ansible_test

Ansible StrictHostKeyChecking

Note: Host key cheking has been turned off in the ansible.cfg file, which makes it possible to run the ping command just as:

$ ansible webservers -m ping -e 'ansible_ssh_user=apache'

If setting this as a default wasn't desired, it's possible to set this at the command line.

$ ansible webservers -m ping -e 'ansible_ssh_user=apache' --ssh-common-args='-o StrictHostKeyChecking=no'

After the first execution of the command with StrictHostKeyChecking=no, the host key is added to knownhosts and you can run the command without host key checking as follows.