sudo cat /etc/sudoers.d/wheel %wheel ALL=(ALL) NOPASSWD: ALL
sudoers: - name: wheel state: present group: wheel runas: ALL commands: ALL nopassword: true
community.general.sudoers: name: "{{ item.name }}" state: "{{ item.state }}" user: "{{ item.user|default(omit) }}" group: "{{ item.group|default(omit) }}" host: "{{ item.host|default(omit) }}" runas: "{{ item.runas|default(omit) }}" commands: "{{ item.commands }}" nopassword: "{{ item.nopassword|default(omit) }}" loop: "{{ sudoers }}"
pyenv install 3.11.4 pyenv local 3.11.4 python3 -m pip install --user ansible==8.0 ansible-core==2.15
pyenv local system python -V Python 2.7.18 pyenv virtualenv system ansible2.10 pyenv local ansible2.10 pip3 install ansible==2.10.7 exec $SHELL -l # confirm pyenv version ansible2.10 ansible --version ansible 2.10.17 config file = /h
µ»ö:
- hosts: localhost connection: local become: no gather_facts: no vars: var1: "aaa" var2: "bbb" tasks: - set_fact: fail_tasks: "{{ fail_tasks|default([]) + [ var1 ~ ':msg1' ] }}" - set_fact: fail_tasks: "{{ fail_tasks|default([]) + [ var2 ~ ':msg2' ] }}" - name: result debug: var: fail_tasks failed_when: yes
ansible-playbook playbook.yml ... TASK [result] **************************************************************************************************************************************** fatal: [localhost]: FAILED! => { "fail_tasks": [ "aaa:msg1", "bbb:msg2" ], "failed_when_result": true }
- name: read tsv read_csv: path: "{{ tsv_path }}" delimiter: "\t" register: lines delegate_to: localhost - name: output tsv with filter debug: var: item when: item['colum 1'] != "" with_items: "{{ lines.list }}"
ansible -i hosts.ini -m setup all \ | perl -ane 's/.+=> {$/{/g;print;' \ | jq '.ansible_facts | [.ansible_hostname, .ansible_distribution, .ansible_distribution_major_version, .ansible_distribution_version] | @tsv' -r \ | sort
module¤È¤Î°ã¤¤
¤è¤¯»È¤¦collection
µ»ö:
- name: warning fail: msg: 'Deprecation Warning: this os is not supported: {{ ansible_os_family }} {{ ansible_distribution_major_version }}' ignore_errors: yes when: ansible_os_family in [ "RedHat" ] and ansible_distribution_major_version|int <= 6
ansible-playbook -i hosts.ini playbook.example.remote-props.yml -e debug=1 -c local ... TASK [debug] ***************************************************************************************************************************************** ok: [127.0.0.1] => { "props": [ { "host": "localhost", "password": "test12345", "user": "test" }, { "host": "localhost", "password": "test2-12345", "user": "test2" } ] }
ansible-playbook -i hosts.ini playbook.example.remote-conf.yml -e debug=1 -c local ... TASK [debug] ***************************************************************************************************************************************** ok: [127.0.0.1] => { "db_hosts": [ { "host": "localhost", "password": "test12345", "user": "test" }, { "host": "localhost2", "password": "test2-12345", "user": "test2" } ] }
ANSIBLE_LOG_PATH=ansible.log ansible-playbook -i hosts playbook.yml
[defaults] log_path=ansible.log
ansible.posix.synchronize: src: "{{ item.src }}" dest: "{{ item.dest }}" ssh_connection_multiplexing: yes use_ssh_args: yes archive: no recursive: yes checksum: yes
- hosts: localhost connection: local vars: var1: - key: key1 val: val1 var2: "{{ var1 | to_nice_json(indent=2) }}" tasks: - copy: content: "{{ var1 | to_nice_json(indent=2) }}" dest: /tmp/example1.json - copy: content: "{{ var2 }}" dest: /tmp/example2.json
cat /tmp/example1.json [ { "key": "key1", "val": "val1" } ] cat /tmp/example2.json [{"key": "key1", "val": "val1"}]
- name: check if java is exists shell: type java register: result changed_when: no ignore_errors: yes - debug: msg="command is not exists" when: result is failed
mkdir library wget -s -O library/fetch_terraform_backend_outputs.py https://raw.githubusercontent.com/katapultcloud/ansible_fetch_terraform_backend_outputs/master/fetch_terraform_backend_outputs.py
param1: "{{ var1 | default(omit) }}"
- group: name: "{{ group_name }}" gid: "{{ group_gid | default(omit,true) }}"
example_major_version: 1 example_param01: example-value01
example_major_version: 1 # example_param01: # ¥³¥á¥ó¥È¥¢¥¦¥È¤·¤Ê¤¤¤È¡¢templateÆâ¤Çvars/°Ê²¼¤ÎÃͤ¬»È¤ï¤ì¤Ê¤¤
- include_vars: "major_version1{{ example_major_version }}.yml"
example_default_param01: 1
param01 = "{{ example_param01 | default(example_default_param01) }}"
role search path is rolename/{files|vars|templates}/, rolename/tasks/.
play search path is playdir/{files|vars|templates}/, playdir/.
# ./foo.txt ¤òroles¤Îtemplate¤Ë¾å½ñ¤¤·¤¿¤¤¡£ # group_vars/all.yaml file1_path: ./foo.txt # roles/example/defaults/main.yml file1_path: foo.txt
- hosts: localhost connection: local become: no gather_facts: no tasks: - debug: var=test_list
ansible-playbook playbook.yml -e '{"test_list": ["a","b","c"]}' ... TASK [debug] **************************************************************************************************************************************************************************** ok: [localhost] => { "test_list": [ "a", "b", "c" ] }
ansible-playbook playbook.yml --syntax-check
diff -up <file.org> <file> > v0.1.patch # git diff¤Ç¤âok git diff origin/master > master-v0.1.patch
JSON¤Ç½ÐÎϤǤ¤Ê¤¤¥³¥Þ¥ó¥É¤Î·ë²Ì¤ò²òÀϤ·¤Æ¡¢ÊÑ¿ô¤ËÊÑ´¹¤·¤Æ¤¯¤ì¤ë¡£
²òÀÏÍѥƥó¥×¥ì¡¼¥È¤òÍÑ°Õ¤¹¤ë¤¬¡¢¥á¥¸¥ã¡¼¤Êµ¡´ïÍѤΥƥó¥×¥ì¡¼¥È¤Ï´û¤Ë¤¢¤ë¡£
Memo/Terraform¤ÇAWS EC2¤òµ¯Æ°¤·¤Æ¡¢ansible-playbook¤ò¼Â¹Ô¤·¤¿¤¤»þ¤Ê¤É¡£
apt: name: "{{ apt_packages }}" state: "{{ item.state }}" update_cache: yes cache_valid_time: 3600
- hosts: - localhost become: False gather_facts: False connection: local vars_prompt: - name: "csv_str" prompt: "Please enter csv" private: no tasks: - set_fact: csv_array: "{{ csv_str.split(',') }}" - debug: msg="{{ item | trim }}" with_items: "{{ csv_array }}"
ansible-playbook playbook.yml Please enter csv: aaa, bbb ok: [localhost] => (item=aaa) => { "changed": false, "item": "aaa", "msg": "aaa" } ok: [localhost] => (item= bbb ) => { "changed": false, "item": " bbb ", "msg": "bbb" }
[DEPRECATION WARNING]: The use of 'include' for tasks has been deprecated. Use 'import_tasks' for static inclusions or 'include_tasks' for dynamic inclusions. This feature will be removed in a future release. Deprecation warnings can be disabled by setting deprecation_warnings=False in ansible.cfg.
Including and Importing — Ansible Documentation
- hosts: all gather_facts: false become: no vars: - pause_seconds: 0 tasks: - ping: - pause: seconds: "{{ pause_seconds }}" when: pause_seconds|int > 0
time ansible-playbook -i test/hosts.ini -l localhost playbook.ping.yml -e 'pause_seconds=60' ... TASK [ping] *************************************************************************************************************************************** ok: [localhost] TASK [pause] ************************************************************************************************************************************** Pausing for 60 seconds (ctrl+C then 'C' = continue early, ctrl+C then 'A' = abort) ok: [localhost] PLAY RECAP **************************************************************************************************************************************** localhost : ok=2 changed=0 unreachable=0 failed=0 real 1m7.318s user 0m4.149s sys 0m0.548s
- name: Remove repository from a specific repo file yum_repository: name: epel file: external_repos state: absent
tasks/main.yml ¤È¤ÏÊ̤Îyaml¤òload¤Ç¤¤ë¡£ tasks¤òʬ³ä¤·¤Æ¡¢ÉáÃʤϼ¹Ԥµ¤ì¤Ê¤¤½èÍý¤òʬ¤±¤é¤ì¤ë¡£
marker: "# {mark} ANSIBLE MANAGED BLOCK {{ item.name }}"
- name: Remove the IP address replace: path: "{{ item }}" regexp: '^.*{{ remove_host }}.*[\r\n]+' with_items: - /etc/hosts.deny
sudo pip install docker-py docker-compose
- hosts: all become: True gather_facts: True tasks: - name: uptime, before reboot shell: uptime | cut -d ',' -f1 register: result_uptime - debug: var: result_uptime.stdout - name: reboot ansible.builtin.reboot: reboot_timeout: 3600 - name: uptime, after reboot shell: uptime | cut -d ',' -f1 register: result_uptime - debug: var: result_uptime.stdout
¡Ösetup¡×¤ÎºÆ¼Â¹Ô¤ÇÎɤ¤ ưŪ¤ËNIC¤òÄɲä·¤¿¸å¤Ë¡¢fact¤Ë¤âÈ¿±Ç¤µ¤»¤¿¤¤¾ì¹ç¤Ê¤É¡£
tasks: - debug: var=ansible_interfaces - yum: name=docker - setup: - debug: var=ansible_interfaces
Î㤨¤Ð¡Öconnection: local¡×¤À¤¬¡¢Ê£¿ô¤Î¡Ögroup_vars/env.yml¡×¤ò´Ä¶Ëè¤ËÀÚ¤êÂؤ¨¤¿¤¤»þ¤Ë»È¤¨¤ë¡£
»ØÄꤷ¤¿group_varsÆâ¤ÎÊÑ¿ô¤¬»²¾È¤Ç¤¤ë¤è¤¦¤Ë¤Ê¤ë¡£
vars_prompt: - name: "inventory_group" prompt: "Please enter inventory_group" private: no tasks: - group_by: key="{{ inventory_group }}" changed_when: False
assemble - Assembles a configuration file from fragments ¡½ Ansible Documentation
[WARNING]: Consider using get_url or uri module rather than running curl
¡Ö-v¡×¥ª¥×¥·¥ç¥ó¤òÉÕ¤±¤¿¤È¤¤Ë¤â¥Ñ¥¹¥ï¡¼¥ÉÅù¤Ï¥³¥ó¥½¡¼¥ë¤Ëɽ¼¨¤·¤¿¤¯¤Ê¤¤¾ì¹çÅù¡£
vars: - show_log: false tasks: - debug: msg="{{ item }}" with_items: "{{ huge_var }}" no_log: "{{ not show_log|bool }}"
ansible -i hosts.ini -m fetch -a 'src=/etc/hosts dest=/tmp/backup/' web* tree -A /tmp/backup/ /tmp/backup/ ¨§¨¡¨¡ web01 ¨¢ ¨¦¨¡¨¡ etc ¨¢ ¨¦¨¡¨¡ hosts ¨¦¨¡¨¡ web02 ¨¦¨¡¨¡ etc ¨¦¨¡¨¡ hosts
- name: Find rpm shell: ls -t $(find /tmp/ -type f -name example-1.0.0-1.rpm) | head -1 register: find_result changed_when: false - name: Get version of installed rpm shell: "rpm -q example | grep -o -P '[\\d\\.\\-]+' | head -n 1" register: installed_version changed_when: false ignore_errors: yes - name: Get version of local rpm shell: "rpm -qp {{ find_result.stdout }} | grep -o -P '[\\d\\.\\-]+' | head -n 1" register: local_version changed_when: false ignore_errors: yes - name: Uninstall package yum: name=example state=absent when: installed_version.rc == 0 and local_version.rc == 0 and installed_version.stdout != local_version.stdout - name: Install package yum: name={{ find_result.stdout }} state=present ignore_errors: "{{ ansible_check_mode }}" - name: Start/stop service service: name=example state={{ example_state }} enabled={{ example_enabled }} ignore_errors: "{{ ansible_check_mode }}"
ansible -i hosts.ini -m copy -a 'content="" dest=/var/spool/mail/user01' --become localhost --check --diff ansible -i hosts.ini -m copy -a 'content="" dest=/var/spool/mail/user01' --become localhost
- file: path: /tmp/dummy state: touch
- lineinfile: dest: /tmp/dummy state: absent regexp: "^.+$" line: "" backup: yes
ansible -i hosts.ini -m shell -a "zgrep Accepted /var/log/secure-20160[7,8]*.gz | grep -o -P 'from ([^\s]+)' | sort | uniq -c | sort -nr" --sudo localhost localhost | SUCCESS | rc=0 >> 79 from 192.168.10.1 22 from 192.168.10.128 22 from 127.0.0.1
yum¥â¥¸¥å¡¼¥ë¤Ç¤Ï¥¤¥ó¥¹¥È¡¼¥ëºÑ¤ß°ìÍ÷¤Ï¼èÆÀ¤Ç¤¤ë¤¬¡¢°ìÉô¤Î¥Ñ¥Ã¥±¡¼¥¸¤À¤±¤Ï»ØÄê¤Ç¤¤Ê¤¤¡£(name¤Èlist¤¬ÇÓ¾»ØÄê)
tasks: - name: yum list installed yum: list=installed register: result ignore_errors: yes changed_when: False - debug: var=result
ok: [127.0.0.1] => { "result": { "changed": false, "results": [ { "arch": "x86_64", "epoch": "0", "name": "MAKEDEV", "nevra": "0:MAKEDEV-3.24-6.el6.x86_64", "release": "6.el6", "repo": "installed", "version": "3.24", "yumstate": "installed" }, ...
ansible -i hosts.ini -m authorized_key -a 'user=user01 key="{{lookup("file","~/.ssh/id_rsa.pub")}}" state=present' --sudo www01
/etc/resolv.conf¤Înameserver¤ÎÃͤò»²¾È¤·¤¿¤¤¡£
ansible -m setup localhost ... "ansible_dns": { "nameservers": [ "192.168.1.1" ], "search": [ "localdomain" ] },
- hosts: all gather_facts: False connection: local vars_prompt: - name: "user_name" prompt: "Please enter name" private: no tasks: - debug: var=user_name
ansible-playbook -i hosts.ini test.yml Please enter name: hoge TASK: [debug var=user_name] *************************************************** ok: [localhost] => { "var": { "user_name": "hoge" } }
ansible-playbook -i hosts.ini test.yml -e "user_name=hogehoge" TASK: [debug var=user_name] *************************************************** ok: [localhost] => { "var": { "user_name": "hogehoge" } }
vars_prompt: - name: "confirm" prompt: "Do you really want to delete ? [yes/no]" private: no tasks: - name: confirm fail: msg="aborted" when: confirm != "yes"
ansible.cfgÆâ¤Ç¡Össh_args = ¡×¤ÇǤ°Õ¤Î¥ª¥×¥·¥ç¥ó¤ò»ØÄê¤Ç¤¤ë¡£
¥Ç¥Õ¥©¥ë¥È¤Î¥ª¥×¥·¥ç¥ó¤Ï¾å½ñ¤¤µ¤ì¤ë¤¿¤á¡¢¥Ç¥Õ¥©¥ë¥È¤Î¥ª¥×¥·¥ç¥ó+ÄɲäΥª¥×¥·¥ç¥ó¤È½ñ¤¤¤¿Êý¤¬Îɤµ¤½¤¦¡£
´Ä¶ÊÑ¿ô¤Ë ANSIBLE_SSH_ARGS ¤¬¤¢¤ë¤È¡¢ansible.cfg¤è¤ê¤âÍ¥À褵¤ì¤ë¡£
[defaults] forks = 5 timeout = 30 # CentOS6¤Çparamiko¤ò»È¤¦¾ì¹ç¡¢False¤Ë¤¹¤ë»ö¤ÇÁ᤯¤Ê¤ë record_host_keys = False [ssh_connection] ansible_connection = ssh ssh_args = -C -o ControlMaster=auto -o ControlPersist=60s -F ssh-config # True¤Ë¤¹¤ë¤È¹â®²½¤¹¤ë¤¬¡¢/etc/sudoers¤Çrequiretty¤ò¥³¥á¥ó¥È¥¢¥¦¥È¤¹¤ëɬÍפ¬¤¢¤ë pipelining = True
- debug: msg="{{ '/etc/httpd/conf/httpd.conf' | basename | regex_replace('\.conf$', '') }}" # httpd
- debug: msg="{{ '/etc/httpd/httpd.conf' | basename | splitext }}" # httpd - debug: msg="{{ '/etc/httpd/httpd.conf.j2' | basename | splitext | first }}" # httpd.conf
phantomjs_install_dir: /usr/local/bin phantomjs_url: - url: https://bitbucket.org/ariya/phantomjs/downloads/phantomjs-1.9.8-linux-x86_64.tar.bz2 sha256sum: "a1d9628118e270f26c4ddd1d7f3502a93b48ede334b8585d11c1c3ae7bc7163a" # sha256sum phantomjs-1.9.8-linux-x86_64.tar.bz2
- name: Download PhantomJS get_url: url={{ phantomjs_url[0].url }} sha256sum={{ phantomjs_url[0].sha256sum }} dest=/tmp/phantomjs.tar.bz2 force=no register: new_archive tags: - phantomjs - name: Unarchive PhantomJS unarchive: src=/tmp/phantomjs.tar.bz2 dest=/tmp copy=no creates=yes when: new_archive|changed tags: - phantomjs - name: Install PhantomJS shell: cp -f /tmp/{{ phantomjs_url[0].url | basename | regex_replace('\.tar\.bz2|\.tar\.gz$', '') }}/bin/phantomjs {{ phantomjs_install_dir }}/ when: new_archive|changed tags: - phantomjs
- hosts: all gather_facts: true become: yes vars: - user_name: user01 - user_groups: - wheel - mysql - debug: 0 pre_tasks: roles: tasks: - name: Check if user exists shell: /usr/bin/id -u {{ item }} register: result_id with_items: user_groups ignore_errors: yes changed_when: False - debug: var=result_id when: debug != 0 - name: Modify user groups user: name={{ user_name }} groups={{ item.item }} append=yes when: item.rc == 0 with_items: "{{ result_id.results }}" handlers: post_tasks:
root¸¢¸Â¤¬É¬Íפʾì¹ç¡¢1.9¤«¤é¡Öbecome: yes¡×¤¬¿ä¾©¡£
¡Ösudo: true¡×¤ÏÈó¿ä¾©¤Ë¤Ê¤Ã¤¿¡£
[defaults] # ÌÀ¼¨Åª¤Ëssh¤ò»È¤¦ transport = ssh [ssh_connection] # sshÀܳ¤ÎºÆÍøÍѤò¤¹¤ë¡£¥¿¥¤¥à¥¢¥¦¥È¤Î»þ´Ö¤ò±ä¤Ð¤¹ ssh_args = -C -o ControlMaster=auto -o ControlPersist=60s -F ssh-config # ¥Û¥¹¥È̾¤¬Ä¹¤¤»þ¤Ë¥¨¥é¡¼¤Ë¤Ê¤ë¤Î¤òËɤ° control_path = %(directory)s/%%h-%%r # True¤Ë¤·¤¿¤¤¾ì¹ç¡¢Á´¥¯¥é¥¤¥¢¥ó¥È¤Î/etc/sudoers¤Îrequiretty¤ò̵¸ú¤Ë¤¹¤ëɬÍפ¬¤¢¤ë¡£sudo»þ¤Ë¥¨¥é¡¼¤Ë¤Ê¤ë¡£ pipelining = True
[ssh_connection] # '%C' by a hash of the concatenation: %l%h%p%r. control_path=%(directory)s/%%C
validate='sshd -t -f %s'
validate='visudo -cf %s'
validate: 'apachectl -t -f %s'
alidate='php -l %s'
sudo yum groupinstall "Japanese Support"
LANG=C yum grouplist -v ... Japanese Support (japanese-support) [ja] ...
- hosts: all sudo: True tasks: - name: yum groupinstall yum: name="{{ packages }}" state=present vars: packages: - "@japanese-support"
git clone https://github.com/ansible/ansible-modules-extras.git export ANSIBLE_LIBRARY=ansible-modules-extras ansible-playbook -i hosts.ini playbook.yml
- hosts: localhost gather_facts: True sudo: False connection: local
- name: Check if Package is installed stat: path: /etc/yum.repos.d/epel.repo register: result ignore_errors: yes changed_when: False # ¥Ñ¥Ã¥±¡¼¥¸¤¬Ìµ¤«¤Ã¤¿¾ì¹ç¤Î½èÍý - debug: var=result when: result.stat.exists == false
- name: Check if Package is installed shell: rpm -q {{ package }} > /dev/null; echo $? args: warn: no register: result ignore_errors: yes changed_when: False # ¥Ñ¥Ã¥±¡¼¥¸¤¬Ìµ¤«¤Ã¤¿¾ì¹ç¤Î½èÍý - debug: var=result when: result.stdout == "0"
stat¤Î¥ª¥×¥·¥ç¥ó | Éÿô |
path¤Î¤ß | 67 |
get_attributes: no | 61 |
get_checksum: no | 63 |
get_mime: no | 67 |
get_attributes: no get_checksum: no | 59 |
- name: Check if git v1 is installed shell: rpm -q git > /dev/null ignore_errors: yes register: result changed_when: False
- name: restart iptables service: name=iptables state=restarted when: ansible_os_family in [ "RedHat" ] and iptables_state == "started"
roles: - { role: andrewrothstein.terraform, tags: terraform }
dependencies: - role: epel vars: epel_enabled: yes
- hosts: webservers roles: - { role: firewalld, when: "ansible_os_family == 'RedHat' and ansible_distribution_major_version|int >= 7" }
- hosts: webservers roles: - { role: some_role, when: "some_role_enabled == 'yes'" }
Developing Modules — Ansible Documentation
- hosts: all gather_facts: True tasks: - shell: test.sh environment: PATH: "/opt/bin:{{ ansible_env.PATH }}" register: result - debug: var=result.stdout
- shell: date environment: TZ: "{{ lookup('env', 'TZ') }}"
TZ=JST ansible-playbook -l 127.0.0.1 -i hosts.ini playbook.yml TZ=UTC ansible-playbook -l 127.0.0.1 -i hosts.ini playbook.yml
- shell: > echo foo; echo var;
/.bashrcÅù¤ÏÆɤ߹þ¤Þ¤ì¤Ê¤¤¡£~/.bashrc ¤ÎÃæ¤ÇPATH¤¬ÀßÄꤵ¤ì¤Æ¤¤¤ë¾ì¹ç¡¢1¹Ô¤Ç¼Â¹Ô¤¹¤ëɬÍפ¬¤¢¤Ã¤¿¡£
# À®¸ù shell: cmd: "/bin/bash -l -c 'tfenv install latest'" # ¼ºÇÔ shell: cmd: "tfenv install latest" executable: "/bin/bash -l"
shell: /path/to/script.sh
msg: Aborting, target uses selinux but python bindings (libselinux-python) aren't installed!
getenforce Permissive
sudo yum install libselinux-python -y
sudo apt install python-selinux
- hosts: 127.0.0.1 gather_facts: False vars: keys: "" tasks: - name: split debug: var="{{ item }}" with_items: "{{ keys.split(',') }}"
ansible-playbook -i hosts.ini test.yaml --extra-vars 'pub_keys=aaa,bbb,ccc' TASK: [split] ***************************************************************** ok: [127.0.0.1] => (item=aaa) => { "aaa": "{{ aaa }}", "item": "aaa" } ok: [127.0.0.1] => (item=bbb) => { "bbb": "{{ bbb }}", "item": "bbb" } ok: [127.0.0.1] => (item=ccc) => { "ccc": "{{ ccc }}", "item": "ccc" }
°Ê²¼¤Î¤è¤¦¤Ë¡¢shell: ¤Î·ë²Ì¤ò¸µ¤ËȽÄꤹ¤ë¤è¤¦¤Ê¾ì¹ç¡¢¡Ö--check¡×¤Ç¤Ï¡¢¥Á¥§¥Ã¥¯task¤¬¼Â¹Ô¤µ¤ì¤Ê¤¤¤¿¤á¡¢¥¨¥é¡¼¤È¤Ê¤ë¤Î¤ò²óÈò¤¹¤ë¡£
- name: check if epel exists shell: rpm -q epel-release > /dev/null; echo $? args: warn: no register: result changed_when: False - name: install epel repository yum: name="http://ftp.riken.jp/Linux/fedora/epel/epel-release-latest-{{ ansible_distribution_major_version }}.noarch.rpm" state=present when: result.stdout != "0" ignore_errors: "{{ ansible_check_mode }}" # ansible 2.1
check_mode: no
ignore_errors: "{{ ansible_check_mode }}"
ansible -i hosts.ini -m copy -a "copy: src=/src/myfiles/foo.conf dest=/etc/foo.conf" --user <username> --ask-pass --sudo <hostname>
ansible -i hosts.ini -m copy -a "copy: src=/src/myfiles/ dest=/tmp/myfiles/" --user <username> --ask-pass --sudo <hostname>
[web]
web01.example.com
web02.example.com
- hosts: web gather_facts: True vars: pre_tasks: - debug: msg="pre_tasks01" roles: - role01 tasks: - name: task01 file: path=/tmp/task01 state=touch notify: handler01 handlers: - name: handler01 debug: msg="handler01" post_tasks: - debug: msg="post_tasks01"
ansible-playbook -i hosts.ini test.yml ... TASK: [debug msg="pre_tasks01"] *********************************************** ok: [web01.example.com] => { "msg": "pre_tasks01" } ok: [web02.example.com] => { "msg": "pre_tasks01" } TASK: [role01 | debug msg="role01"] ******************************************* ok: [web02.example.com] => { "msg": "role01" } ok: [web01.example.com] => { "msg": "role01" } TASK: [task01] **************************************************************** changed: [web02.example.com] changed: [web01.example.com] NOTIFIED: [handler01] ********************************************************* ok: [web01.example.com] => { "msg": "handler01" } ok: [web02.example.com] => { "msg": "handler01" } TASK: [debug msg="post_tasks01"] ********************************************** ok: [web01.example.com] => { "msg": "post_tasks01" } ok: [web02.example.com] => { "msg": "post_tasks01" } PLAY RECAP ******************************************************************** web01.example.com : ok=6 changed=1 unreachable=0 failed=0 web02.example.com : ok=6 changed=1 unreachable=0 failed=0
- name: Create directory file: path=/tmp/test_dir state=directory owner=root group=root mode=0755 - name: Create symlink file: src=/tmp/test_dir dest=/tmp/test_link state=link
when: ansible_distribution_major_version|int >= 7
when: is_enabled|bool
# ansible 2.9.6 ¤Ç¤Ï whenÁ´ÂΤò¥À¥Ö¥ë¥¯¥ª¡¼¥È¤Ç°Ï¤à¤È¡¢¾ï¤ËÀ®¸ù¤Ë¤Ê¤Ã¤Æ¤·¤Þ¤Ã¤¿¤Î¤ÇÉÔÍÑ when: 'str1' in result # ¤½¤ì°ÊÁ°¤Ç¤Ï¡¢¥À¥Ö¥ë¥¯¥ª¡¼¥È¤Ç³ç¤é¤Ê¤¤¤È¥¨¥é¡¼¤Ë¤Ê¤ë¤Ï¤º when: "'str1' in result"
when: ansible_distribution in [ 'CentOS', 'Red Hat Enterprise Linux' ]
# ¥Ñ¥¹¥ï¡¼¥É¤Ë¿ô»ú¤¬Æþ¤Ã¤Æ¤Ê¤¤¾ì¹ç¤ò¥Á¥§¥Ã¥¯ when: password is not regex('\d+') # ÀèƬ°ìÃס£"| match(str)" ¤Ïv2.9¤ÇÇÑ»ßͽÄê¡£ when: ansible_hostname is match("^web") # Éôʬ°ìÃ× when: ansible_hostname is search("web") # ¤½¤ì°Ê³°¤ÎÀµµ¬É½¸½ when: ansible_hostname is regex("web")
when: result is failed when: result is succeeded when: result is skipped # ÈÝÄê¤Ï when: var1 is not skipped
when: (result.var1 | default("")) != "foo"
result.failures = [ "~All matches were filtered out by exclude filtering for argument:~", "~All matches were filtered out by exclude filtering for argument:~", ]
when: 'exclude filtering' not in result.failures
when: not (result.failures | regex_search('exclude filtering'))
- hosts: 127.0.0.1 gather_facts: False tasks: - name: test local_action: shell exit 2 register: result failed_when: result.rc > 2 - debug: var=result
- name: Stop services service: name="{{ item }}" state=stopped enabled=no with_items: - cups ignore_errors: yes
- copy: dest: /var/www/html/test.html content: | <html lang="ja"> <head><meta charset="UTF-8"><title>test title</title></head> <body>test body</body> </html>
- name: Add user to the sudoers lineinfile: dest: "/etc/sudoers.d/user01" owner: root group: root mode: "0440" state: present create: yes regexp: "^user01 .*" line: "user01 ALL=(ALL) NOPASSWD{{':'}} ALL" validate: 'visudo -cf %s'
¥Ç¥Õ¥©¥ë¥È¤Ç¤Ïtty¤Ê¤·¤Îssh¤Ç¤Ï¡¢sudo¤Ç¤¤Ê¤¤¤è¤¦¤ËÀßÄꤵ¤ì¤Æ¤¤¤ë¾ì¹ç¤¬Â¿¤¤¡£
sudo visudo -- Defaults requiretty Defaults:root !requiretty --
sudo visudo -- user: !requiretty %group: !requiretty --
ansible -i hosts -m ping all
Àܳ¤Ëssh¤ò»È¤¦¤è¤¦¤Ë¤·¡¢ssh¦¤Ç¿ÃÊÀßÄê¤ò¤¹¤ë¡£
¥Û¥¹¥È¤ÎÀܳ¤Ë¤Ï̾Á°¤ò»È¤¦¡£DNS¤ÏÉÕ¤±¤Ê¤¯¤Æ¤âÎɤ¤¡£
Host * StrictHostKeyChecking=no UserKnownHostsFile=/dev/null LogLevel ERROR ForwardAgent yes Host gateway.host HostName 192.168.1.10 User gw_user IdentityFile ~/.ssh/id_rsa ProxyCommand none Host other.host HostName 192.168.1.11 User other_user IdentityFile /.ssh/id_rsa ProxyCommand ssh -F ssh-config -W %h:%p gateway.host
ssh -F ssh-config other.host
ansible hosts.ini -m ping other.host
ssh-agent bash ssh-add ~/.ssh/id_rsa
# »Ä¤Ã¤Æ¤¤¤ëansible ssh¥×¥í¥»¥¹¤ò½ªÎ» killall ansible vi ansible.cfg ---- [defaults] forks = 5 ----
vim stg.hosts ---- [stg:children] stg_web [stg_web] stg-web-[01:02].example.com [stg_web:vars] ansible_ssh_user=ec2-user ansible_ssh_private_key_file=~/.ssh/stg-web.pem ----
ansible -i stg.hosts -m shell -a 'rpm -qv bash' stg stg-web-01.example.com | success | rc=0 >> bash-4.1.2-9.el6_2.x86_64 stg-web-02.example.com | success | rc=0 >> bash-4.1.2-15.el6_5.2.x86_64
ansible --sudo -i stg.hosts -m shell -a 'yum -y update bash' stg
YAMLÃæ¤Ç"foo: bar"¤Îʸ»úÎó¤À¤ÈSyntax Error¤¬È¯À¸¤¹¤ë¡£"foo:bar"¤ÏÌäÂê¤Ê¤¤¡£
- hosts: 127.0.0.1 vars: colon: ':' tasks: # - debug: msg="foo: bar" # Syntax Error - debug: msg="foo:bar" # OK - debug: msg="foo{{ colon }} bar" # OK - debug: msg="foo"":"" bar" # OK(1.9) / NG(2.0) - debug: msg="foo{{':'}} bar" # OK(1.9) / OK(2.0)
ansible-playbook colon.yml TASK: [debug msg="foo:bar"] *************************************************** ok: [127.0.0.1] => { "msg": "foo:bar" } TASK: [debug msg="foo{{ colon }} bar"] **************************************** ok: [127.0.0.1] => { "msg": "foo: bar" } TASK: [debug msg="foo"":"" bar"] ********************************************** ok: [127.0.0.1] => { "msg": "foo\"\":\"\" bar" } TASK: [debug msg="foo: bar"] ************************************************** ok: [127.0.0.1] => { "msg": "foo: bar" }
- debug: msg: "{{ item.stdout_lines | replace('\\t',' ') }}"
--- - hosts: localhost connection: local gather_facts: false become: false vars: - msg1: | first line. second line, inventory_hostname: {{ inventory_hostname }} - users: - user: user1 email: user1@example.com - user: user2 email: user2@example.com tasks: - debug: var: msg1 - debug: msg: - first line - second line - debug: msg: "{{ msg1.split('\n') }}" - debug: msg: "{{ _msg.split('\n') }}" with_items: "{{ users }}" vars: _msg: | User: {{ item.user }} Email: {{ item.email }}
ansible-playbook playbook.yml ... TASK [debug] ******************************************************************************************************************************************************* ok: [localhost] => { "msg1": "first line.\nsecond line, inventory_hostname: localhost\n" } TASK [debug] ******************************************************************************************************************************************************* ok: [localhost] => { "msg": [ "first line", "second line" ] } TASK [debug] ******************************************************************************************************************************************************* ok: [localhost] => { "msg": [ "first line.", "second line, inventory_hostname: localhost", "" ] } TASK [debug] ******************************************************************************************************************************************************* ok: [localhost] => (item={u'user': u'user1', u'email': u'user1@example.com'}) => { "msg": [ "User: user1", "Email: user1@example.com", "" ] } ok: [localhost] => (item={u'user': u'user2', u'email': u'user2@example.com'}) => { "msg": [ "User: user2", "Email: user2@example.com", "" ] } ...
- hosts: 127.0.0.1 tasks: - name: job1 debug: msg="job1" tags: - job1 - name: job2 debug: msg="job2" tags: - job2 - name: job2 debug: msg="job3" tags: - job3
# job1, job2¤À¤±¼Â¹Ô ansible-playbook -t job1,job2 tags.yml # job2 °Ê³°¤ò¼Â¹Ô ansible-playbook --skip-tags job2 tags.yml
Î㤨¤Ðpre_task:¤Ç¥Á¥§¥Ã¥¯½èÍý¤ò¤·¤Æ¤¤¤ë¾ì¹ç¡¢-t ¤Ç¥¿¥°»ØÄꤷ¤¿¾ì¹ç¼Â¹Ô¤µ¤ì¤Ê¤¤¡£
pre_tasks: - block: - name: Validate OS fail: msg="Unsupported OS{{':'}} {{ ansible_os_family }}" when: ( ansible_os_family not in [ "RedHat" ] ) tags: - always - validate
ansible -i hosts.ini -m ping all
ansible -i hosts.ini -m ping webservers:dbservers
ansible -i hosts.ini -m ping webservers:\!web03
vim hosts.ini ---- [web] web01 ansible_ssh_host=192.168.61.101 ---- ansible -i hosts.ini -m ping web01
[stg_web] stb_web_[01:02] [stg_web:vars] ansible_ssh_user=ec2-user ansible_ssh_private_key_file=~/.ssh/ec2-user.pem
group_vars/stg_web host_vars/stb_web_01
[stg:children] stg_web stg_DB [prod:children] prod_web prod_db [stg_web] stg_web_01 [stg_DB] stg_db_01 [prod_web] prod_web_01 [prod_db] prod_db_01
ansible stg_web_01 -i hosts -m shell -a 'uname -a'
ansible stg_web -i hosts -m shell -a 'uname -a'
ansible-playbook -l prod -i hosts playbook.yml
ansible-playbook *_web_01 -i hosts playbook.yml
tasks: # OS¥Õ¥¡¥ß¥ê¡¼Ëè¤Ë»ØÄê - include: RedHat.yml when: ansible_os_family in [ "RedHat" ] - include: Debian.yml when: ansible_os_family in [ "Debian" ] # ¥Ç¥£¥¹¥È¥ê¥Ó¥å¡¼¥·¥ç¥óËè¤Ë»ØÄê - yum: name=ntp state=installed when: ansible_distribution in [ 'CentOS', 'Red Hat Enterprise Linux' ] - apt: name=ntp state=installed when: ansible_distribution in [ 'Debian', 'Ubuntu' ] - service: name=ntpd state=started enabled=yes
- name: disable Defaults requiretty lineinfile: dest: /etc/sudoers regexp: '^(Defaults\s+requiretty)$' line: '#\1' backrefs: true validate: 'visudo -cf %s' backup: true
- lineinfile: dest: test.txt regexp: '^#?\s*key=' line: 'key=value' state: present