Ansible Cheat Sheet

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 8

SSH Setup GALAXY

Copy your Ansible Master's public key to the managed install Role (Module)
node ansible-galaxy install
ssh-keygen ## generate public key geerlingguy.nginx
ssh-copy-id <name of node> # copy key,
provide password to node

configure Hosts file


/etc/ansible/hosts
[production] PLAYBOOKS
prod1.prod.local run playbook with sudo
prod2.prod.local ansible-playbook -v config-
users.yaml --sudo --sudo-user=joe
[dev] --ask-sudo-pass
devweb1.dev.local
devweb2.dev.local
use different Hosts file
ansible-playbook -v -i
REMOTE CMD (Ad Hoc) /path/to/hosts

Ping specific node run playbook but only a specific task (tag)
ansible -i hosts nycweb01.prod.local -m ansible-playbook
ping playbooks/restore_bitbucket.yaml -
i hosts --tags rsync
Ping with wildcard
ansible -i hosts "nycweb*" -m ping
or to skip: (--skip-tags tag1,
tag2)
Ping all nodes with SSH user 'root'
ansible -i hosts all -m ping -u root
store output of a command as a variable
shell: cat /etc/network | grep
run a command eth0
ansible -i hosts dev -a 'uname -a'
register: address
debug: msg="address is {{
check Yum packages address.stdout }}"
ansible -i hosts dev -m yum

check if Docker rpm is installed configure multiple items with one task
ansible -i hosts web01.nyc.local -m
shell -a "rpm -qa | grep docker"
- name: more complex items to add
several users
Get facts about a box user:
ansible -i hosts web01.nyc.local -m name: "{{ item.name }}"
setup -a 'filter=facter_*' uid: "{{ item.uid }}"
groups: "{{ item.groups }}"
run command with sudo state: present
ansible -i hosts target-host -m shell -a with_items:
"cat /etc/sudoers" --sudo - { name: testuser1, uid:
1002, groups: "wheel, staff" }
limit command to a certain group or server: add -- - { name: testuser2, uid:
limit *.nyc 1003, groups: staff }

get path location of current Playbook (pwd)


{{ playbook_dir }}
Set playbook to be verbose by
SERVER DIAGNOSTICS default

Test Connection - hosts: blah


ansible -i hosts all -m ping -u root
strategy: debug
Diagnostics

run playbook with verbose traceback


ansible-playbook -i hosts
manage nodes via "/etc/ansible/hosts" file myPlaybook.yaml -vvv

Debug (debug output for playbook) run playbook on multiple Host groups
- debug: var=result verbosity=2 - hosts: "search_head, deployer"

Run playbook locally on host

hosts: 127.0.0.1
PACKAGES AND INSTALLATION connection: local

install multiple packages Prompt for password during Playbook run


yum: name="{{ item }}" state=present
with_items: # Playbook to change user password
- http
- htop - name: pw change
- myapp hosts: target
become: true
become_user: root
vars_prompt:
- name: username
prompt: "enter username for
JOBS AND PROCESS CONTROL which to change the pw"
run Ansible ad hoc with 10 parallel forks - name: password
ansible -i hosts testnode1 -a "uname -a" prompt: "enter new password"
-f 10 private: yes

show human readable output tasks:


add this line to ansible.cfg - name: change pw
stdout_callback=yaml user: "name={{ username }}
password={{ password }}
update_password=always"

run playbook with "dry run" / NOOP / simulate


ansible-playbook foo.yml --check
CONDITIONALS
Run task on different target,
y file to n
- name: run something on some
other server
debug: msg="running stuff"
delegate_to: someserver

VARIABLES Delegate task to a host group


- name: restart web servers
service: name=memcached
include global variables for all Roles
state=restarted
delegate_to: "{{ item }}"
sample playbook
with_items: "{{
splunk/
groups['webservers'] }}"
setup_splunk_playbook.yaml
roles/base Get IP or facter of a remote host
/tasks/main.yaml - name: get IP
/tasks/install.yaml debug: msg="{{
search_head hostvars['nycweb01']['ansible_defa
/tasks/configure.yaml ult_ipv4']['address'] }}"
indexer
/tasks/configure.yaml or
some_other_role
/tasks/some_task.yaml debug: msg="{{
hosts hostvars[item]['ansible_ssh_host']
config.yaml }}"
Place your vars into config.yaml with_items: "{{
groups['webservers'] }}"
cat splunk/config.yaml
synchronize file (copy file from Ansible host to
---
target)
# global Splunk variables
splunk_version: 7.0.0 - synchronize:
src: "{{ playbook_dir
in your playbook, include the Roles }}/files/vscode.repo"
dest: /etc/yum.repos.d/
cat setup_splunk_playbook.yaml
- hosts: "search_heads" synchronize from server A to server B with a
become_user: root wildcard
become: true - name: copy Splunk Apps
gather_facts: true synchronize:
src:
roles: "/opt/splunk/etc/apps/{{ item }}"
- base (server A)
- search_head dest:
in your Role, include the Global Vars inside a "/opt/splunk/etc/shcluster/apps/"
Task (server B)
with_items:
cat roles/base/tasks/main.yaml - item1
--- - item2
# install Splunk Base delegate_to: server A

- name: include vars wget a file to a location


- get_url:
include_vars: "{{ playbook_dir
url:
}}/config.yaml"
'https://dl.google.com/go/go1.10.l
inux-amd64.tar.gz'
- include: install.yaml dest: '/tmp'
vars are accessible in tasks now, force: no # dont download
if file already exists
cat roles/base/tasks/install.yaml
untar tar.gz
- name: echo version
debug: splunk version is {{
splunk_version }} USER AND GROUP MGMT
Loop through a Dict variable inside a playbook
change user password for user Joe (user Fred
cluster: running the cmd as sudo on the target box)
members:
splunk01: 10.123.1.0 # 1 install passlib
splunk02: 10.123.1.1 pip install passlib
splunk03: 10.123.1.2
#2 update the pw, using a hash
in the playbook, ansible targethost -s -m user -a
- debug: msg="{{ "name=joe update_password=always
cluster.members.values() | password={{ 'MyNewPassword' |
map('regex_replace', '(.*)', password_hash('sha512') }}" -u
'https://\\1:8089') | join(',') }}" fred --ask-sudo-pass

>> https://10.123,1.0:8089,
copy public ssh key to remote
https://10.123.1.1:8089, etc etc
authorized_keys file

Use Inventory file variables inside a playbook - hosts: targetHost


tasks:
cat hosts - name: update nessus SSH keys
[apache] become_user: root
nycweb01 become_method: sudo
become: true
playbook
debug: msg="IP: {{ authorized_key:
hostvars[groups['apache'][0]]['ansible_d user: nessus
efault_ipv4']['address'] }}" key: "{{ lookup('pipe','cat
debug: msg="Hostname: {{ ../files/ssh_keys/nessus.pub') }}"
hostvars[groups['apache'][0]]['inventory
state: present
_hostname'] }}"

register a List/Array to be used for later,


- name: parse all hostnames in group
WebServer and get their IPs, place them
in a list FILES & DIRS
command: echo {{
hostvars[item]['ansible_ssh_host'] }}" delete all files and hidden files in a directory
vars:
with_items: "{{ groups['webserver']
app_home: /var/opt/application
}}"
register: ip_list
tasks:
- name: clear home dir
- name: show the IPs
- shell: "ls -la {{ app_home
debug: msg={{ ip_list.results |
}}/"
map(attribute='item') | list }}"
register: files_to_delete
- file: path="{{ app_home }}/{{
item }}" state=absent
export an Environment variable
with_items: "{{
- name: yum install
files_to_delete.stdout_lines }}"
yum: name=somepkg state=present
environment:
SOME_VAR: abc get files from node
ansible node1 -s -m fetch -a
"src=/etc/hosts dest=/tmp"

Variables inside Inventory Hosts file copy file to node


cat hosts ansible node1 -m copy -a
[web] "src=/etc/hosts dest=/tmp/hosts"
nycweb01.company.local
remove all files matching a wildcard
[web:vars] file: path={{ item }} state=absent
role="super duper web server" with_fileglob: /tmp/*.rpm

now get the "role" variable inside the playbook,


- hosts: web
gather_facts: true FACTER
tasks:
- name: print Role var get all facts from a node (ad hoc)
debug: msg={{ role }} ansible -i hosts targetName -m
setup -a "filter="facter_*"
// super duper web server
use fact in a playbook
include fact as {{
ansible_factname }}

add fact to Hosts file


[group]
MODULES host1 admin_user=jane
service: name=httpd state=[started, host2 admin_user=jack
stopped, restarted, reloaded] host3
enabled=[yes,no]
user: name=joe state=[present,absent] [group:vars]
uid=1001 groups=wheel shell=/bin/bash admin_user=john
group: name=splunk gid=6600
state=[present,absent] system=[yes/no] get default IPV4 address
yum: name=apache state=[present, latest, ansible_default_ipv4.address
absent, removed]
file: path=/etc/file state=[file, link, Local facts
directory, hard, touch, absent] group=x
owner=x recurse=yes place .fact file into
/etc/ansible/facts.d on target
node
vim
/etc/ansible/facts.d/fruits.fact

[fruits]
sweet=banana, apple, grapes
bitter=grapefruit

get Local facts


ansible -i hosts mrx -m setup -a
"filter=ansible_local"
What you need to know
 You generated, on your computer, both a public and private key. They are stored in
the ~/.ssh folder, and are just files stored on your hard drive, usually
named id_rsa.pub (public key) and id_rsa (private key). GitHub has a nice guide to help you
generate those keys.
 You had to give GitHub your public key in order for them to authenticate you. That’s perfectly
normal, that’s why it’s called public. Go to github.com/settings/ssh to see them.
 Your private key is really important. If someone steals it, they can impersonate you, and that’s bad
as they could have access to your private repos or git push as you.
 That’s why you should always protect your private key with a strong passphrase. The private key
is just a file on your disk, if left unencrypted, anybody with a USB key and access to your laptop can
steal it and use it.

Mã hóa bất đối xứng



 Nếu bạn đã từng sử dụng một remote Git server như Github, Gitlab hay Bitbbucket hoặc một server
Git do công ty bạn tự dựng thì chắc hẳn bạn đã từng gặp phải trường hợp cần nhập username và
password đối vỡi mỗi lần muốn push code hay pull code từ server đó về. Tuy nhiên để tránh phải
nhập username và password mỗi lần như vậy thì thông thường ta sẽ thêm RSA public key của mình
vào server đó. Cặp public-private key này thường được chúng ta sinh ra trên máy tính cá nhân với 2
file lần lượt là :
 id_rsa: chứa private key và chúng ta cần bảo vệ private key này không cho ai nó lộ ra ngoài
 id_rsa.pub: chưa public key và đây là key mà chúng ta sẽ thêm vào server git
 Sau này mỗi khi chúng ta muốn tương tác với server thì trước hết sẽ cần phải tạo một kết nối đến nó
giống như khi chúng ta sử dụng username và password. Tuy nhiên khi bạn đã có cặp private-public
key và public key đã được thêm trên server thì khi chúng ta mới tạo kết nối sẽ diễn ra quá trình xác
thực căn bản như sau (ở đây mình muốn giải thích cho các bạn về việc ứng dụng mã hóa RSA trong
SSH nên sẽ chỉ nói về phần này):
 Đầu tiền khi tạo kết nối ta sẽ gửi kèm với định danh của chúng ta là public key
 Server sẽ kiểm tra danh sách các public key mà nó có và tất nhiên vì chúng ta đã thêm public key này
từ trước đó nên server sẽ tìm thấy. Server sẽ dùng public key mà chúng ta cung cấp này để mã hóa
một challenge hoặc các bạn có thể hiểu đơn giản là một chuỗi giữ liệu nào đó ví dụ abcdef và gửi lại
cho client
 Ở client vì chuỗi abcdef nói trên được mã hóa bằng thuật toán bất đối xứng RSA và public key mà
chúng ta đăng kí với server nên tất nhiên bằng cách sử dụng private key trên máy chúng ta để giải
mã sẽ thua được chuỗi abcdef đó. Sau khi giải mã ta sẽ gửi lại chuỗi cho Server và lúc này Server có
thể xác thực cho yêu cầu kết nối của chúng ta. Ở đây vì cặp private-public key này là do chính ta sinh
ra và cho nên nếu bất cứ giữ liệu nào được mã hóa bằng public key thì chỉ có thể giải mã
bằng private key tương ứng.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy