ansible-playbookでオプションを使おう

–syntax-checkでチェックする

[vagrant@host ~]$ ansible-playbook playbook.yml –syntax-check
[DEPRECATION WARNING]: Instead of sudo/sudo_user, use become/become_user and
make sure become_method is ‘sudo’ (default).
This feature will be removed in a
future release. Deprecation warnings can be disabled by setting
deprecation_warnings=False in ansible.cfg.

playbook: playbook.yml

–list-task でタスク一覧を表示

[vagrant@host ~]$ ansible-playbook pbook.yml –list-task
[DEPRECATION WARNING]: Instead of sudo/sudo_user, use become/become_user and
make sure become_method is ‘sudo’ (default).
This feature will be removed in a
future release. Deprecation warnings can be disabled by setting
deprecation_warnings=False in ansible.cfg.

playbook: pbook.yml

play #1 (all): all TAGS: []
tasks:
add a new user TAGS: []

playbook: playbook.yml

play #1 (all): all TAGS: []
tasks:
add a new user TAGS: []
install libselinux-python TAGS: []

play #2 (web): web TAGS: []
tasks:
install apache TAGS: []
start apache and enabled TAGS: []
change owner TAGS: []
copy index.html TAGS: []
install php packages TAGS: []
copy hello.php TAGS: []

play #3 (db): db TAGS: []
tasks:
install mysql TAGS: []
start mysql and enabled TAGS: []
create a database TAGS: []
create a user for mydb TAGS: []

playbook.ymlを編集する

---
- hosts: all
  sudo: yes
  tasks:
    - name: add a new user
      user: name=hpscript state=absent

Whether the account should exist or not, taking action if the state is different from what is stated.

[vagrant@host ~]$ ansible-playbook pbook.yml
[DEPRECATION WARNING]: Instead of sudo/sudo_user, use become/become_user and
make sure become_method is ‘sudo’ (default).
This feature will be removed in a
future release. Deprecation warnings can be disabled by setting
deprecation_warnings=False in ansible.cfg.

PLAY [all] *********************************************************************

TASK [setup] *******************************************************************
ok: [192.168.43.52]
ok: [192.168.43.53]

TASK [add a new user] **********************************************************
changed: [192.168.43.53]
changed: [192.168.43.52]

PLAY RECAP *********************************************************************
192.168.43.52 : ok=2 changed=1 unreachable=0 failed=0
192.168.43.53 : ok=2 changed=1 unreachable=0 failed=0

ssh接続する
[vagrant@host ~]$ ssh web
Last login: Tue Oct 2 18:17:56 2018 from 192.168.43.51
[vagrant@web ~]$ cat /etc/passwd

ぬお、hpscriptが居なくなっている! すげーーーーーーーー

ssh接続してcatしよう

ユーザー一覧を表示する

[vagrant@web ~]$ cat /etc/passwd

apache:x:48:48:Apache:/var/www:/sbin/nologin
hpscript:x:503:503::/home/hpscript:/bin/bash

/etc/passwd とは?
>このファイルには、ユーザがログインする際に必要なユーザ名や、ホームディレクトリなど、各種の設定が書かれています。以前は、パスワードを暗号化したものが、このファイルに一緒に書かれていましたが、セキュリティを強化するため、パスワードを暗号化したものは、/etc/shadow ファイルに書かれるようになりました。

root:x:0:0:root:/root:/bin/bash
bin:x:1:1:bin:/bin:/sbin/nologin
daemon:x:2:2:daemon:/sbin:/sbin/nologin
adm:x:3:4:adm:/var/adm:/sbin/nologin

なるほど~ 色々なユーザーがおりますな。

ansible document
https://docs.ansible.com/
https://docs.ansible.com/ansible/latest/modules/modules_by_category.html

sytem moduleのuserを見る。
https://docs.ansible.com/ansible/latest/modules/user_module.html#user-module

ERROR! playbooks must be a list of plays

---
- hosts: all
  sudo: yes
  tasks:
    - name: add a new user
      user: name=hpscript

[vagrant@host ~]$ ansible-playbook pbook.yml
ERROR! playbooks must be a list of plays

なに!?

[vagrant@host ~]$ ansible-playbook pbook.yml
[DEPRECATION WARNING]: Instead of sudo/sudo_user, use become/become_user and
make sure become_method is ‘sudo’ (default).
This feature will be removed in a
future release. Deprecation warnings can be disabled by setting
deprecation_warnings=False in ansible.cfg.

PLAY [all] *********************************************************************

TASK [setup] *******************************************************************
ok: [192.168.43.52]
ok: [192.168.43.53]

TASK [add a new user] **********************************************************
changed: [192.168.43.53]
changed: [192.168.43.52]

PLAY RECAP *********************************************************************
192.168.43.52 : ok=2 changed=1 unreachable=0 failed=0
192.168.43.53 : ok=2 changed=1 unreachable=0 failed=0

おお、インデントを直したら通った

同じコマンドをもう一回打つと、
PLAY RECAP *********************************************************************
192.168.43.52 : ok=2 changed=0 unreachable=0 failed=0
192.168.43.53 : ok=2 changed=0 unreachable=0 failed=0

ほう、changed=0になりましたね♪

ansibleを触っていこう

[vagrant@host ~]$ ansible –version
ansible 2.2.0.0
config file = /home/vagrant/ansible.cfg
configured module search path = Default w/o overrides

ansibleってレッドハットが所有してるんだ。どうりで。
https://www.ansible.com/

[vagrant@host ~]$ ssh web
Last login: Wed Nov 23 22:41:13 2016 from 192.168.43.51
[vagrant@web ~]$ exit
logout
Connection to 192.168.43.52 closed.
[vagrant@host ~]$ ssh db
Last login: Wed Nov 23 22:41:12 2016 from 192.168.43.51
[vagrant@db ~]$ exit
logout
Connection to 192.168.43.53 closed.

なんじゃこりゃー

inventry file

[web]
192.168.43.52

[db]
192.168.43.53

[vagrant@host ~]$ ansible all -i hosts -m ping
192.168.43.53 | SUCCESS => {
“changed”: false,
“ping”: “pong”
}
192.168.43.52 | SUCCESS => {
“changed”: false,
“ping”: “pong”
}

ansible.cfg

[defaults]
hostfile = ./hosts

[vagrant@host ~]$ ansible all -m ping
192.168.43.53 | SUCCESS => {
“changed”: false,
“ping”: “pong”
}
192.168.43.52 | SUCCESS => {
“changed”: false,
“ping”: “pong”
}

eclipseでmysqlに接続(3時間かかったーーーーー)

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		//		response.getWriter().append("Served at: ").append(request.getContextPath());
		Connection conn = null;
		Statement stmt = null;
		ResultSet rs = null;

		try {
		  Class.forName("com.mysql.jdbc.Driver").newInstance();
		  conn = DriverManager.getConnection("jdbc:mysql://localhost/sampledb?user=root&password=");
		  stmt = conn.createStatement();
		  rs = stmt.executeQuery("SELECT userid,status FROM userinfo");
		  
		  response.setContentType("text/plain");
		  while (rs.next()) {
		    response.getWriter().write("userid=" + rs.getString("userid") + ", ");
		    response.getWriter().write("status=" + rs.getString("status") + "\n");
		  }
		} catch(Exception e) {
		  e.printStackTrace();
		} finally {
		  if (rs != null ) { try {rs.close(); } catch (SQLException e) {e.printStackTrace();} }
		  if (stmt != null ) { try {stmt.close(); } catch (SQLException e) {e.printStackTrace();} }
		  if (conn != null ) { try {conn.close(); } catch (SQLException e) {e.printStackTrace();} }
		}
		
	}

見よ、涙の結晶を!! これだけで3時間くらいかかった。

疲れたので、あまり喜べない。。。
とりあえず、tomcat + servlet + jspで mysql、redirectまでは解った!!! 
すげーーーーーーーーーーーーーーーー
mysql connectorは鬼門だった。。
さあ~ ansible 行ってみよう♪♪♪♪♪ 

Loading class `com.mysql.jdbc.Driver’. This is deprecated.

Loading class `com.mysql.jdbc.Driver’. This is deprecated.

以下に変更

Class.forName("com.mysql.cj.jdbc.Driver").newInstance();

Loading class `com.mysql.jdbc.Driver’. This is deprecated. The new driver class is `com.mysql.cj.jdbc.Driver’. The driver is automatically registered via the SPI and manual loading of the driver class is generally unnecessary.
java.sql.SQLException:

connectorがどうもおかしいっぽい。
なんか違うなーと思ったらconnector/jか! 間際らしい。

mysql-connector

eclipseのlibにmysql-connectorを配置する

servletを作成する。mysqltestとしよう。

add to build pathとする

とりあえずwindows10 のmysqlにテーブルとレコードを無理矢理つくります。
mysql> create database sampledb
-> ;
Query OK, 1 row affected (0.13 sec)

mysql> use sampledb
Database changed
mysql> create table userinfo(
-> userid varchar(10) primary_key,
-> status Int
-> );
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ‘primary_key,
status Int
)’ at line 2
mysql> create table userinfo(
-> userid varchar(10) primary key,
-> status int
-> );
Query OK, 0 rows affected (1.04 sec)

mysql> insert into userinfo (userid, status) values (“aaaa123”, 0),(“asdf123”, 1),(“xyzx123”,2);
Query OK, 3 rows affected (0.17 sec)
Records: 3 Duplicates: 0 Warnings: 0

mysql> select * from userinfo;
+———+——–+
| userid | status |
+———+——–+
| aaaa123 | 0 |
| asdf123 | 1 |
| xyzx123 | 2 |
+———+——–+
3 rows in set (0.00 sec)

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		//		response.getWriter().append("Served at: ").append(request.getContextPath());
		Connection conn = null;
		Statement stmt = null;
		ResultSet rs = null;

		try {
		  Class.forName("com.mysql.cj.jdbc.Driver").newInstance();
		  conn = DriverManager.getConnection("jdbc:mysql:C:/mysql-56/data/sampledb?user=root&password=");
		  stmt = conn.createStatement();
		  rs = stmt.executeQuery("SELECT userid,status FROM userinfo");
		  
		  response.setContentType("text/plain");
		  while (rs.next()) {
		    response.getWriter().write("userid=" + rs.getString("userid") + ", ");
		    response.getWriter().write("status=" + rs.getString("status") + "\n");
		  }
		} catch(Exception e) {
		  e.printStackTrace();
		} finally {
		  if (rs != null ) { try {rs.close(); } catch (SQLException e) {e.printStackTrace();} }
		  if (stmt != null ) { try {stmt.close(); } catch (SQLException e) {e.printStackTrace();} }
		  if (conn != null ) { try {conn.close(); } catch (SQLException e) {e.printStackTrace();} }
		}
		
	}

Loading class `com.mysql.jdbc.Driver’. This is deprecated. The new driver class is `com.mysql.cj.jdbc.Driver’. The driver is automatically registered via the SPI and manual loading of the driver class is generally unnecessary.
java.sql.SQLException: No suitable driver found for jdbc:mysql:C:/mysql-56/data/sampledb?user=root&password=
at java.sql.DriverManager.getConnection(Unknown Source)

やりたいことはわかった。

servletのリダイレクト処理

doGetなどは関係ないが、とにかく、response.sendRedirect(url);でリダイレクトができる。

package todo.controller;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 * Servlet implementation class HelloServlet
 */
@WebServlet("/HelloServlet")
public class HelloServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public HelloServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
    	request.setAttribute("foo", "hogehoge");

		String view = "/WEB-INF/view/index.jsp";
		RequestDispatcher dispatcher = request.getRequestDispatcher(view);

		dispatcher.forward(request, response);
	}
	

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		String value = request.getParameter("hoge");
		System.out.println(value);
		String url = "http://www.google.com";
		response.sendRedirect(url);
//		doGet(request, response);
	}

}

jspは省略
postを受け取って、redirect

OKOK。次はmysql接続